扩展运算符将一个数组转为用逗号分隔的参数序列;
- console.log(...[1, 2, 3]) //1 2 3
- // (1) 将一个数组, 变为参数序列
- let add = (x, y) => x + y;
- let numbers = [1, 2];
- console.log(add(...numbers))//3
- // (2) 使用扩展运算符展开数组代替 apply 方法, 将数组转为函数的参数
- // ES5 取数组最大值
- console.log(Math.max.apply(this, [654, 233, 727])); //727
- // ES6 扩展运算符
- console.log(Math.max(...[654, 233, 727])) //727
- // 相当于
- console.log(Math.max(654, 233, 727))//727
- // (3) 使用 push 将一个数组添加到另一个数组的尾部
- // ES5 写法
- let arr1 = [1, 2, 3];
- let arr2 = [4, 5, 6];
- Array.prototype.push.apply(arr1, arr2);
- console.log(arr1) // [1, 2, 3, 4, 5, 6]
- // push 方法的参数不能是数组, 通过 apply 方法使用 push 方法
- // ES6 写法
- let arr3 = [1, 2, 3];
- let arr4 = [4, 5, 6];
- arr3.push(...arr4);
- console.log(arr3) // [1, 2, 3, 4, 5, 6]
- // (4) 合并数组
- let a = ['a', 'b'];
- let b = ['c'];
- let c = ['d', 'e'];
- // ES5 的合并数组
- let d = a.concat(b, c);
- console.log(d) //["a", "b", "c", "d", "e"]
- // ES6 的合并数组
- let e = [...a, ...b, ...c]
- console.log(e) //["a", "b", "c", "d", "e"]
- // (6) 将字符串转换为数组
- let h = [...'hello']
- console.log(h) //["h", "e", "l", "l", "o"]
- // ES5
- let str = 'world'.split('') //["w","o","r","l","d"]
- console.log(str)
- // (6) 转换伪数组为真数组
- var nodeList = document.querySelectorAll('p');
- console.log(nodeList)
- var array = [...nodeList];
- console.log(array)
- // 具有 iterator 接口的伪数组, 非 iterator 对象用 Array.from 方法
- // (7)map 结构
- let map = new Map([
- [1, 'one'],
- [2, 'two'],
- [3, 'three'],
- ]);
- let arr = [...map.keys()];
- console.log(arr) //[1, 2, 3]
参考文档:
es6 三点扩展运算符 https://www.cnblogs.com/rlann/p/7222150.html
来源: http://www.bubuko.com/infodetail-3122905.html