0

This doesn't work. b is just full of undefined.

const a = new Array(100);
b = a.map((c, idx) => idx);
console.log(b);

If I spread a into a new bracketed array, b contains the indices as expected:

const a = [...new Array(100)];
b = a.map((c, idx) => idx);
console.log(b);

What's going on here? Is there some difference in the arrays created with [] and new Array()?

As far as I know, new Array(n) is the only easy way to create an array with a number of elements.

Cheers.

Adam Palmer
  • 221
  • 2
  • 3
  • _"new Array(n) is the only easy way to create an array with a number of elements"_ - No, it isn't. `new Array(n)` does nothing more than setting the `.length` property of the array: [`23.1.1.1 Array ( ...values )`](https://tc39.es/ecma262/#sec-array) -> 5.e `Perform ! Set(array, "length", intLen, true)` – Andreas Mar 05 '21 at 12:02
  • Both examples end up with `b` being an array of 100 empty slots? I assume if you want a quick array with the items being 1..N. Use `new Array(100).fill('').map((c, idx) => idx)` – evolutionxbox Mar 05 '21 at 12:03
  • @evolutionxbox `Array.from({ length: 100 }, (_, i) => i)` – Andreas Mar 05 '21 at 12:45
  • @Andreas that is magic! – evolutionxbox Mar 05 '21 at 12:47

0 Answers0