let a = {0: 'a', 1: 'b', length: 2}
Array.apply(null, a) // ['a', 'b']
Using the Array constructor is the fastest way to convert an Array-like Object to Array e.g. jsperf
I want to figure out how it works but I failed. In ECMAScript-262, I can't find the corresponding approach to explain that code.
Why the Array constructor accept an array-like object can turn it to an Array.
Difference between Array.apply(null, Array(x) ) and Array(x)
Why does Array.apply(null, [args]) act inconsistently when dealing with sparse arrays?
When using
Function#apply(), the second parameter takes an array-like. An array-like is basically an object that has numeric keys and alengthproperty but isn't necessarily an array - for example theargumentsobject is an array-like.That parameter will then be supplied to the function you call
applyon as if it is all the arguments for that function:So, when you call
Array.apply(null, {0: 'a', 1: 'b', length: 2})that is equivalent to the callArray('a', 'b')- using the array constructor with multiple arguments produces an array from those arguments:Thus when you call
applyon the constructor function you get that behaviour.In ES6, passing an array as a second argument to
.applyis almost the same as using the spread syntax:However, this doesn't work with array-likes: