0

I'm trying to fill an Array created using Array(5) with the index of each element:

let arr = Array(5)

arr.forEach((item, index) => arr[index] = index)

console.log(arr)

// expected output:
// [0, 1, 2, 3, 4]

// instead I get 
// [
//   undefined,
//   undefined,
//   undefined,
//   undefined,
//   undefined
// ]

Where am I mistaken?

connexo
  • 53,704
  • 14
  • 91
  • 128
  • So it's actually possible to have an Array with an iterable length but no indices? That does not make much sense to me. – connexo Mar 10 '18 at 20:34
  • that *only* happens when you do that. If you said `new Array(3, 5);` you'd get `[3, 5]`. Additionally, there's no need to construct arrays that way, you don't have to specify the length ahead of time the way you would in C. You could always just do `Array.apply(null, Array(5))` and it will work as expected. – Jared Smith Mar 10 '18 at 20:48

1 Answers1

2

You need to fill it with function .fill()

That array is actually empty, so the forEach doesn't iterate.

new Array(arrayLength)

arrayLength

If the only argument passed to the Array constructor is an integer between 0 and 232-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). If the argument is any other number, a RangeError exception is thrown.

let arr = Array(5).fill();
arr.forEach((item, index) => { arr[index] = index })
console.log(arr);

Why does my code work when I change the first line to let arr = [...Array(5)]?

let arr = Array(5); 
Array.from(arr) // equals to [...arr];

.apply "expands" the elided elements into proper arguments, and the results ends up being something like Array(undefined, undefined, undefined, undefined, undefined) Reference

Community
  • 1
  • 1
Ele
  • 33,468
  • 7
  • 37
  • 75
  • The iteration **does** take place, only `index` is obviously `undefined` in each iteration. Otherwise how do I get an Array containing 5 `undefined` values? Why does my code work when I change the first line to `let arr = [...Array(5)]`? – connexo Mar 10 '18 at 20:37
  • 1
    If you put a `console.log(…)` into the forEach method you can see that the interation does not take place; the method is not called. Do you, in your original example, really get “five undefined values?” I get “five empty slots,” and that's not the same. – Renardo Mar 10 '18 at 20:48
  • @connexo see the updated answer. – Ele Mar 10 '18 at 20:52
  • Uh, no, `[...arr]` does not equal to `Array.apply(null, arr)`. It's the same as `Array.from(arr)` though. – Bergi Mar 10 '18 at 21:15
  • @Bergi you're right will use the `length` attribute. However, the apply function will return an array with the `n` elements. – Ele Mar 10 '18 at 21:20