Reputation: 8424
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);
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? Can we somehow translate this object to an array to get this result? I've tried many things to do this, but without success.
Upvotes: 3
Views: 80
Reputation: 943510
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
.
The second argument for apply
is an array-like object which gives the list of arguments.
If you had [0, 0, 0]
then that would be like this object:
{
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.
The arguments you pass to Array
become its initial values.
Now, it seems that (internally) Array
checks the length
of its arguments
and then sets its internal values using something like:
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]
.
Upvotes: 3
Reputation: 13211
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:
Array.apply(null, ["a",,"b"])
// [ 'a', undefined, 'b' ]
Upvotes: 1