0

new Array(n) will create an array of n * undefined, so why can't you use new Array(n).map((_, index) => index) function to get [0, 1, 2 ..., n-1 ] What about arrays like this?

I know that new Array(n).fill(0).map((_, index) => index) is ok, but is there any essential difference between the two arrays of n * undefined and n * 0 ?

Common pits for initializing an n*m two-dimensional array:

  • Wrong way 1: new Array(n).fill(new Array(m).fill(0)) All arrays point to the same reference
  • Wrong way 2: new Array(n).map(v => new Array(m).fill(0)) "ghost array" problem
  • Correct way 1: new Array(n).fill(0).map(v => new Array(m).fill(0))

2 Answers 2

2

From the MDN Web Docs:

If the only argument passed to the Array constructor is an integer [...] this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values)

So like they say, it just sets the length, it doesn't set any of the values. So if the array contains no elements, then you can't map a non-existent value into a function.

Sign up to request clarification or add additional context in comments.

Comments

1

Array Document

If the only argument passed to the Array constructor is an integer between 0 and 2^32 - 1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values — see sparse arrays). If the argument is any other number, a RangeError exception is thrown.

Array(n) or new Array(n) produces arrays with only length and no elements, so I call them "ghost arrays". Such an array cannot be traversed correctly with forEach or map (because there are no elements), but it is amazing that it has [@@iterator], which can be traversed using for ... of, or expanded into an array using the spread operator (eg [...Array(10)]), and can be converted using Array.from().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.