简体   繁体   English

将扩展语法与函数参数对象一起使用

[英]Using spread syntax with function Arguments object

I know one has to be very careful with the function Arguments object我知道必须非常小心函数Arguments 对象

But are there any known downsides (optimization/performance issues) to using the spread syntax with the Arguments object?但是,将扩展语法与 Arguments 对象一起使用是否有任何已知的缺点(优化/性能问题)? Or is this totally okay?或者这完全没问题?

I want to create an array from an unknown amount of arguments passed to a function:我想从传递给函数的未知数量的参数中创建一个数组:

function Numbers(){
    this.numbers = [...arguments];
}

A fiddle can be found here可以在这里找到小提琴

It looks quite neat, and in the MDN page about the Arguments object is even suggested that I can use spread syntax for this:它看起来很整洁,在关于 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正如您可以使用任何类似 Array 的对象一样,您可以使用 ES2015 的Array.from()方法或扩展语法arguments转换为真正的 Array

But I still would like see if others have another opinion on this.但我还是想看看其他人是否对此有不同的看法。

You can also use rest parameters :您还可以使用休息参数

function Numbers(...numbers){
    this.numbers = numbers;
}

Using a spread does the same thing cleaner in ES2015在 ES2015 中使用传播可以使同样的事情更干净

this.numbers = [...arguments];

Just remember that this won't work in arrow functions (no arguments ) , and you're good.请记住,这在箭头函数(无arguments )中不起作用,并且您很好。 Rest arguments and Array.from are other options that are fine as well. Rest 参数和 Array.from 是其他很好的选项。

The old-fashioned ES5 is:老式的 ES5 是:

this.numbers = [].slice.call(arguments);

It's fine to use spread notation (it's not an operator) with arguments .使用带有arguments扩展符号(它不是运算符)很好。 Or at least, it's as fine as it ever is to use arguments .或者至少,使用arguments和以往一样好。 In ES2015 and above (eg, if you have spread notation), there's very limited call to use arguments .在 ES2015 及更高版本中(例如,如果您使用了扩展符号),对 use arguments调用非常有限。

And indeed, there's no need in your example: Use rest arguments:实际上,您的示例中不需要:使用其余参数:

function Numbers(...args){
    this.numbers = args;
}

In that example, args is an array.在那个例子中, args是一个数组。 A true array.一个真正的数组。

One reason people say not to use the arguments object is because it looks like an array but its not:人们说不要使用 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.例如,它没有 pop 方法。 However it can be converted to a real Array:但是它可以转换为一个真正的数组:

You're good to go here because, like Array.from() the spread operator makes a new copy你很高兴来到这里,因为像 Array.from() 一样,展开运算符会创建一个新副本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM