将扩展语法与函数 Arguments 对象一起使用
Using spread syntax with function Arguments object
我知道必须非常小心地使用函数 Arguments object
但是对 Arguments 对象使用扩展语法是否有任何已知的缺点(optimization/performance 问题)?或者这完全没问题?
我想根据传递给函数的未知数量的参数创建一个数组:
function Numbers(){
this.numbers = [...arguments];
}
它看起来很整洁,在关于 Arguments 对象的 MDN 页面中甚至建议我可以为此使用扩展语法:
As you can do with any Array-like object, you can use ES2015's Array.from()
method or spread syntax to convert arguments
to a real Array
不过我还是想看看大家对此有没有其他看法
使用 spread 在 ES2015 中做同样的事情更干净
this.numbers = [...arguments];
请记住,这在箭头函数中不起作用 (否 arguments
),你很好。其余参数和 Array.from 也是其他选项。
老式的ES5是:
this.numbers = [].slice.call(arguments);
你也可以使用rest parameters:
function Numbers(...numbers){
this.numbers = numbers;
}
在 arguments
中使用扩展符号(它不是运算符)很好。或者至少,它和使用 arguments
一样好。在 ES2015 及更高版本中(例如,如果你有扩展符号),使用 arguments
.
的调用非常有限
事实上,您的示例中没有必要:使用剩余参数:
function Numbers(...args){
this.numbers = args;
}
在那个例子中,args
是一个数组。真正的数组。
人们说不使用 arguments 对象的一个原因是因为它看起来像一个数组,但它不是:
The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:
你很高兴去这里,因为像 Array.from() 一样,传播运算符会制作一个新副本
我知道必须非常小心地使用函数 Arguments object
但是对 Arguments 对象使用扩展语法是否有任何已知的缺点(optimization/performance 问题)?或者这完全没问题?
我想根据传递给函数的未知数量的参数创建一个数组:
function Numbers(){
this.numbers = [...arguments];
}
它看起来很整洁,在关于 Arguments 对象的 MDN 页面中甚至建议我可以为此使用扩展语法:
As you can do with any Array-like object, you can use ES2015's
Array.from()
method or spread syntax to convertarguments
to a real Array
不过我还是想看看大家对此有没有其他看法
使用 spread 在 ES2015 中做同样的事情更干净
this.numbers = [...arguments];
请记住,这在箭头函数中不起作用 (否 arguments
),你很好。其余参数和 Array.from 也是其他选项。
老式的ES5是:
this.numbers = [].slice.call(arguments);
你也可以使用rest parameters:
function Numbers(...numbers){
this.numbers = numbers;
}
在 arguments
中使用扩展符号(它不是运算符)很好。或者至少,它和使用 arguments
一样好。在 ES2015 及更高版本中(例如,如果你有扩展符号),使用 arguments
.
事实上,您的示例中没有必要:使用剩余参数:
function Numbers(...args){
this.numbers = args;
}
在那个例子中,args
是一个数组。真正的数组。
人们说不使用 arguments 对象的一个原因是因为它看起来像一个数组,但它不是:
The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:
你很高兴去这里,因为像 Array.from() 一样,传播运算符会制作一个新副本