• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home » Resolved: new Array(n).map((_, index) => index) cannot initialize an array

Resolved: new Array(n).map((_, index) => index) cannot initialize an array

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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))

Answer:

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().

If you have better answer, please add a comment about this, thank you!

array-algorithms
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Shopware 400 Status Error “This value is too long. It should have 255 character or less.” When I Try Updating Database Table

01/04/2023

Resolved: Using AWK to count multiple patterns in a file

01/04/2023

Resolved: significance letter above bar graphic in wrong order

01/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.