陣列分隔合併

spread 運算子

Version >= 6

使用 ES6,你可以使用擴充套件將單個元素分隔為逗號分隔語法:

let arr = [1, 2, 3, ...[4, 5, 6]];  // [1, 2, 3, 4, 5, 6]

// in ES < 6, the operations above are equivalent to
arr = [1, 2, 3];
arr.push(4, 5, 6);

spread 運算子還對字串起作用,將每個單獨的字元分隔為一個新的字串元素。因此,使用陣列函式將這些轉換為整數,上面建立的陣列等效於下面的陣列:

let arr = [1, 2, 3, ...[..."456"].map(x=>parseInt(x))]; // [1, 2, 3, 4, 5, 6]

或者,使用單個字串,可以簡化為:

let arr = [..."123456"].map(x=>parseInt(x)); // [1, 2, 3, 4, 5, 6]

如果未執行對映,則:

let arr = [..."123456"]; // ["1", "2", "3", "4", "5", "6"]

spread 運算子也可用於將引數傳播到函式中

function myFunction(a, b, c) { }
let args = [0, 1, 2];

myFunction(...args);

// in ES < 6, this would be equivalent to:
myFunction.apply(null, args);

rest 運算子

其餘運算子通過將多個元素合併為單個元素來與擴充套件運算子相反

[a, b, ...rest] = [1, 2, 3, 4, 5, 6]; // rest is assigned [3, 4, 5, 6]

收集函式的引數:

function myFunction(a, b, ...rest) { console.log(rest); }

myFunction(0, 1, 2, 3, 4, 5, 6); // rest is [2, 3, 4, 5, 6]