1. 拓展运算符
// 对象合并 let obj = { a: 0 }; let obj1 = { a1: 1 }; let obj2 = { a2: 2 }; // 方式一(繁琐) obj.a1 = obj1.a1; obj.a2 = obj2.a2; // 方式二(简洁) obj = { ...obj1, ...obj2 }; // 数组合并 let arr = []; let arr1 = [1, 2]; let arr2 = [3, 4]; // 方式一(繁琐) arr = arr.concat(arr1); arr = arr.concat(arr2); // 方式二(简洁) arr = [...arr1, ...arr2];
2. 解构赋值
// 对象 let res = { detail: { a: 1, b: 2, c: 3, }, }; // 方式一(繁琐) const a = res.detail.a; const b = res.detail.b; const c = res.detail.c; // 方式二(简洁) const { a, b, c } = res.detail; // 数组 let arr = [1, 2, 3]; // 方式一(繁琐) const a = arr[0]; const b = arr[1]; const c = arr[2]; // 方式二(简洁) const [a, b, c] = arr;
3. 拼接字符串
// 模板字符串 let title = "标题"; let text = "文本"; // 方式一(繁琐) let htmlStr = "<div>"; "<h1>" + title + "</h1>"; "<p>这是" + text + "</p>"; ("</div>"); // 方式二(简洁) let htmlStr = ` <div> <h1>${title}</h1> <p>这是${text}</p> </div> `;
4. 对象属性定义
// 动态属性名 const dynamic = "color"; const item = { brand: "Ford", [dynamic]: "Blue", }; console.log(item); // { brand: "Ford", color: "Blue" } // 带条件的对象属性 const getUser = (emailIncluded) => { return { name: "John", surname: "Doe", ...(emailIncluded ? { email: "john@doe.com" } : null), }; }; const user = getUser(true); console.log(user); // outputs { name: "John", surname: "Doe", email: "john@doe.com" } const userWithoutEmail = getUser(false); console.log(userWithoutEmail); // outputs { name: "John", surname: "Doe" }