数组分隔合并
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]