I'm want to quickly construct an array of n length using the array constructor Array() and then loop over the resulting array.
Per MDN's docs:
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 length set to that number. If the argument is any other number, a RangeError exception is thrown.
Presumably, executing Array(5) creates an array with a length of 5, which it does.
var arr = new Array(5);
console.log(arr); // [undefined x 5]
console.log(arr.length); // 5
However, when I try to loop over the resulting array and log out the values or the index, nothing happens.
arr.forEach(function(v, i) { console.log(v, i); });
// nothing logs to the console
Alternatively, if I use an array literal, and try to loop over the values, it logs as expected:
[undefined, undefined].forEach(function(v, i) { console.log(v, i); });
// undefined 0
// undefined 1
Why can't I loop over an array created by the Array constructor?
This answer explains some of the browser strangeness that occurs with map, example:
arr.map(function(v, i) { return i; }) // returns [undefined x 5]
But I'm particularly interested in why the forEach loop doesn't iterate at all over the values.
[,,].forEach(console.log.bind(console, 'Log: '))also seems broken :)Array.apply(null, new Array(5)).forEach(console.log.bind(console))okforEach.forEachfails to iterate at all, as opposed tomapwhich does iterate, but has unexpected values.mapis not iterated neither:Array(5).map(function(){ alert("You won't see me") })