I want to quickly build an array of length n using the array constructor Array() , and then go through the resulting array.
Per MDN docs :
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 the length set to that number. If the argument is any other number, a RangeError exception is thrown.
Presumably, executing Array(5) creates an array of length 5, which it makes.
var arr = new Array(5); console.log(arr);
However, when I try to iterate over the resulting array and exit the values ββor index, nothing happens.
arr.forEach(function(v, i) { console.log(v, i); });
Alternatively, if I use an array literal and try to loop over the values, it is logged as expected:
[undefined, undefined].forEach(function(v, i) { console.log(v, i); });
Why can't I iterate over the array created by the Array constructor?
This answer explains some browser oddities that occur with map , for example:
arr.map(function(v, i) { return i; })
But I am particularly interested in why the forEach loop does not iterate over all values.
source share