Question:
newArray(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))
Answer:
Array DocumentIf 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()
.If you have better answer, please add a comment about this, thank you!