Array.map doesn't seem to work on uninitialized arrays

arrays, javascript

Solution

If you'd like to fill an array, you can use `Array(5).fill()` and the methods will then work as expected--see the alternate related answer from aasha7. Older pre-fill approaches include:

Array.apply(null, new Array(5)).map(function() { return 0; });
// [ 0, 0, 0, 0, 0 ]

After some reading one of the posts linked in the comments, I found this can also be written as

Array.apply(null, {length: 5}).map(function() { return 0; });

However, trying to use `.map` on undefined values will not work.

x = new Array(10);
x.map(function() { console.log("hello"); });

// so sad, no "hello"
// [ , , , , , , , , ,  ]

`.map` will skip over undefined values :(

Problem

I'm trying to set default values on an uninitialized array using the map function but it doesn't seem to work, any ideas on how to set default values? Consider this code snippet I tried in Chrome console. ``` > var N = 10; > var x = new Array(N); > x [undefined x 10] > x.map(function(i) { return 0;}); [undefined x 10] ``` I was expecting the array to be initialized to 0's.

Original source

Related problems