Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

javascript - Difference between Array.apply(null, Array(x) ) and Array(x)

What exactly is the difference between:

Array(3)
// and
Array.apply(null, Array(3) )

The first returns [undefined x 3] while the second returns [undefined, undefined, undefined]. The second is chainable through Array.prototype.functions such as .map, but the first isn't. Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a difference, a quite significant one.

The Array constructor either accepts one single number, giving the lenght of the array, and an array with "empty" indices is created, or more correctly the length is set but the array doesn't really contain anything

Array(3); // creates [], with a length of 3

When calling the array constructor with a number as the only argument, you create an array that is empty, and that can't be iterated with the usual Array methods.

Or... the Array constructor accepts several arguments, whereas an array is created where each argument is a value in the array

Array(1,2,3); // creates an array [1,2,3] etc.

When you call this

Array.apply(null, Array(3) )

It get's a little more interesting.

apply accepts the this value as the first argument, and as it's not useful here, it's set to null

The interesting part is the second argument, where an empty array is being passed in.
As apply accepts an array it would be like calling

Array(undefined, undefined, undefined);

and that creates an array with three indices that's not empty, but have the value actually set to undefined, which is why it can be iterated over.

TL;DR
The main difference is that Array(3) creates an array with three indices that are empty. In fact, they don't really exist, the array just have a length of 3.

Passing in such an array with empty indices to the Array constructor using apply is the same as doing Array(undefined, undefined, undefined);, which creates an array with three undefined indices, and undefined is in fact a value, so it's not empty like in the first example.

Array methods like map() can only iterate over actual values, not empty indices.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...