简体   繁体   English

这个Array.apply方法如何工作?

[英]How does this Array.apply method works?

I understand you can pass an array to Function.prototype.apply but recently I've come across this code (it was written as a good way to create an array with undefined values as opposed to empty slots or holes); 我知道你可以将一个数组传递给Function.prototype.apply但是最近我遇到了这个代码(它是一个很好的方法来创建一个带有undefined值而不是空槽或孔的数组);

var a = Array.apply( null, { length: 3 } );

I can't understand how this code works starting with the second argument. 从第二个参数开始,我无法理解这段代码是如何工作的。 Is there another syntax that could be used to make it more understandable what's going on? 是否有其他语法可用于使其更容易理解发生了什么? What's going on when we pass an actual object to apply as opposed to an array? 当我们传递一个实际的对象来apply而不是一个数组时会发生什么? Can we somehow translate this object to an array to get this result? 我们可以以某种方式将此对象转换为数组以获得此结果吗? I've tried many things to do this, but without success. 我已经尝试了许多方法来做到这一点,但没有成功。

Oh, that is just horrible. 哦,那太可怕了。

So, when you call Array as a function, it doesn't really care what this is so you can tell it that this is null . 所以,当你把Array作为一个函数调用时,它并不关心this是什么,所以你可以告诉它thisnull

The second argument for apply is an array-like object which gives the list of arguments. apply的第二个参数是一个类似于数组的对象 ,它给出了参数列表。

If you had [0, 0, 0] then that would be like this object: 如果你有[0, 0, 0]那么就像这个对象:

{
    0: 0,
    1: 0,
    2: 0,
    length: 3
}

… because arrays get a length property which equals the value of their highest index. ...因为数组获得的长度属性等于其最高索引的值。 A real array would get other properties from the prototype, but we (and apply , and Array ) don't care about them. 一个真正的数组将从原型中获得其他属性,但我们(和applyArray )并不关心它们。

The arguments you pass to Array become its initial values. 传递给Array的参数将成为其初始值。

Now, it seems that (internally) Array checks the length of its arguments and then sets its internal values using something like: 现在,似乎(内部) Array检查其argumentslength ,然后使用以下内容设置其内部值:

for (var i = 0; i < arguments.length; i++) {
    internal_array_values.push(arguments[0])
}

And if you have an object which consists solely of { length: 3 } it is going to get undefined as the value of each of those three arguments giving you [undefined, undefined, undefined] . 如果你有一个仅由{ length: 3 }组成的对象,它将被undefinedundefined的三个参数中的每一个的值给你[undefined, undefined, undefined]

http://www.2ality.com/2012/07/apply-tricks.html http://www.2ality.com/2012/07/apply-tricks.html

With apply and Array (which can be used as either a function or a constructor), you can turn holes into undefined elements: 使用applyArray (可以用作函数或构造函数),可以将孔转换为未定义的元素:

 Array.apply(null, ["a",,"b"])
  // [ 'a', undefined, 'b' ]

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

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