擴展運算符將一個數組轉爲用逗號分隔的參數序列node
console.log(...[a, b, c]) // a b c
用於:數組
1 將一個數組,變爲參數序列app
let add = (x, y) => x + y; let numbers = [3, 45]; console.log(add(...numbers))//48
2 使用擴展運算符展開數組代替apply方法,將數組轉爲函數的參數函數
//ES5 取數組最大值 console.log(Math.max.apply(this, [654, 233, 727])); //ES6 擴展運算符 console.log(Math.max(...[654, 233, 727])) //至關於 console.log(Math.max(654, 233, 727))
3 使用push將一個數組添加到另外一個數組的尾部this
// ES5 寫法 var arr1 = [1, 2, 3]; var arr2 = [4, 5, 6]; Array.prototype.push.apply(arr1, arr2);
//push方法的參數不能是數組,經過apply方法使用push方法 // ES6 寫法 let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; arr1.push(...arr2);
4 合併數組spa
var arr1 = ['a', 'b']; var arr2 = ['c']; var arr3 = ['d', 'e']; // ES5 的合併數組 arr1.concat(arr2, arr3); // [ 'a', 'b', 'c', 'd', 'e' ] // ES6 的合併數組 [...arr1, ...arr2, ...arr3] // [ 'a', 'b', 'c', 'd', 'e' ]
5 將字符串轉換爲數組prototype
[...'hello'] // [ "h", "e", "l", "l", "o" ] //ES5 str.split('')
6 轉換僞數組爲真數組code
var nodeList = document.querySelectorAll('p'); var array = [...nodeList];
//具備iterator接口的僞數組,非iterator對象用Array.from方法
7 map結構對象
let map = new Map([ [1, 'one'], [2, 'two'], [3, 'three'], ]); let arr = [...map.keys()]; // [1, 2, 3]