(...)ES6三點擴充套件運算子
阿新 • • 發佈:2018-12-09
擴充套件運算子將一個陣列轉為用逗號分隔的引數序列
console.log(...[a, b, c]) // a b c
用於:
1 將一個數組,變為引數序列
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將一個數組新增到另一個數組的尾部
// 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 合併陣列
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 將字串轉換為陣列
[...'hello'] // [ "h", "e", "l", "l", "o" ] //ES5 str.split('')
6 轉換偽陣列為真陣列
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]