es6使用小技巧
①模板字符串拼接字符``
`${name}小朋友,欢迎你加入${school}`
name和school皆为变量
②定义变量,使用const和let来代替var,避免变量上升,污染全局变量
③合并对象:展开运算符
const obj1 = { a: 1, b: 2 }; const obj2 = { c: 3, d: 4 }; const obj = { ...obj1, ...obj2};
使用 Object.assign()
const obj1 = { a: 1, b: 2 }; const obj2 = { c: 3, d: 4 }; const obj = Object.assign({}, obj1, obj2); console.log(obj); // 输出:{a: 1, b: 2, c: 3, d: 4}
注意两者区别,和深浅拷贝问题
④解构赋值
const user = { name: 'LiHua', age: 18, sex: 'male', address: 'Shanghai' }; const { name, age } = user; // LiHua 18
⑤语法糖async/await使用
async function getData() { return new Promise((resolve, reject) => { setTimeout(() => { resolve('data'); }, 3000); }); } async function fetchData() { const data = await getData(); console.log(data);//3后打印 } fetchData();