ES6
// 解构赋值const { a, b, c, d, e } = obj || {};// 扩展运算const obj = { ...obj1, ...obj2 }; //{a:1,b:1}// 模板字符串const result = `${name}${score > 60 ? "的考试成绩及格" : "的考试成绩不及格"}`;// 条件判断if ([1, 2, 3, 4].includes(type)) {//...}// find 返回第一个匹配的元素const array = [5, 12, 8, 130, 44];const found = array.find(e => e > 10);console.log(found);//12
reduce
函数接收4个参数:上一个归并值、当前项、当前项的索引和数组本身。
调函数第一次执行时,accumulator 和currentValue的取值有两种情况:
- 如果调用reduce()时提供了initialValue,accumulator取值为initialValue,currentValue取数组中的第一个值;
- 如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。
求和
let values = [1, 2, 3, 4, 5];let sum = values.reduce((prev, cur, index, array) => prev + cur);alert(sum); // 15let sum2 = values.reduce((accumulator, currentValue, currentIndex, array) => {return accumulator + currentValue}, 10)alert(sum2); // 25
合并对象
var obj1 = {fruits: ['Banana', 'Mango'],vegetables: ['Potato', 'Broccoli'],};var obj2 = {store: 'Walmart',};function merge(...arr){return arr.reduce((acc, val) => {return { ...acc, ...val };}, {});}var obj3 = merge(obj1, obj2);console.log(obj3);// {fruits: ["Banana", "Mango"], vegetables: ["Potato", "Broccoli"], store: "Walmart"}
扩展运算符
ES2018 将这个运算符引入了对象
数组
扩展运算符(spread)是三个点(…)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
console.log(...[1, 2, 3]) //1 2 3// ES6 的写法let arr1 = [0, 1, 2];let arr2 = [3, 4, 5];arr1.push(...arr2);
- 接受参数 ```javascript function f(x, y, z) { // … } let args = [0, 1, 2]; f(…args);
function push(array, …items) { array.push(…items); }
```javascriptconst a1 = [1, 2];const a2 = [...a1]; //浅拷贝,// ES6 的合并数组[...arr1, ...arr2, ...arr3]// 解构赋值,只能放在参数的最后一位const [first, ...rest] = [1, 2, 3, 4, 5];first // 1rest // [2, 3, 4, 5]//任何定义了遍历器(Iterator)接口的对象,都可以用扩展运算符转为真正的数组。[...'hello']// [ "h", "e", "l", "l", "o" ]
对象
解构赋值
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };x // 1y // 2z // { a: 3, b: 4 }
接收参数
function wrapperFunction({ x, y, ...restConfig }) {// 使用 x 和 y 参数进行操作// 其余参数传给原始函数return baseFunction(restConfig);}
let aClone = { ...a };// 等同于let aClone = Object.assign({}, a);let ab = { ...a, ...b };// 等同于let ab = Object.assign({}, a, b);
one-line
//生成随机字符串 36j进制 0-9 a-zMath.random().toString(36).slice(2) // '3ukic6ijxzw'
