ES6引入了一个新的运算符 ... 通常称为spread/rest(展开或收集)运算符,取决于它在哪使用
function foo(x,y,z) {
console.log( x, y, z );
}
foo( ...[1,2,3] );
当 ... 用在数组之前时(实际上是任何 iterable (可迭代的)),它会把这个变量展开为各个独立的值。
var a = [2,3,4];
var b = [ 1, ...a, 5]
console.log( b ); //[1,2,3,4,5]
在这种用法中, ... 基本上代替了 concat(...) ,等价的语句 [1].concat( a, [5] )
... 的另一种常见用法基本上可以被看成反向的行为, 把一系列的值收集成为一个数组
function foo(x, y, ...z) {
console.log( x, y, z )
}
foo ( 1, 2, 3, 4, 5 );
在这段代码中, ...z基本上是在说:把剩下的参数收集到一起组成一个名为z的数组
没有命名参数的话, ... 就会收集所有的参数
function foo(...args) {
console.log( args );
}
foo(1, 2, 3, 4, 5); //[1,2,3,4,5];
这种用法为arguments提供了很好的替代,在ES6之前,因为arguments是类数组,而不是真正的数组,在使用某些特性的时候,我们需要把arguments转换数组,但现在args直接就是参数数组,使用会方便很多
// ES6的写法
function foo(...args) {
args.shift(); //丢弃第一个元素
console.log( ...args );
}
//ES5的写法
function bar() {
//将arguments转换为一个真正的数组
var args = Array.prototype.slice.call( arguments );
//在尾端添加几个元素
args.push ( 4, 5 );
//过滤掉奇数
args = args.filter( function(v) {
return v % 2 == 0;
});
//将args传给foo(...)
foo.apply( null, args);
}
bar( 0, 1, 2, 3 ); // 2 4
465

被折叠的 条评论
为什么被折叠?



