The reason this isn't working, seems to be because forEach
isn't iterating the undefined
values that are set when using the array constructor like that.
forEach
works fine for arrays that actually have contents, as you will seen when you run code like this:
[1,2,3,4,5,6,7,8].forEach(function(){console.log(arguments)});
So, now, all you'd be looking for would be to properly initialize a new array, with contents.
This question on SO has some useful answers in that regard.
The shortest solution seems to be:
new Array(5+1).join('0').split('')
You can simply chain the forEach
after that.
Or, you can whip up a prototype from one of the more upvoted answers in that question:
Array.prototype.init = function(value, length){
return Array.apply(null, new Array(length)).map(function(){
return value.valueOf();
},value);
}
That allows you to do something like this:
[].init('foo', 3);
// ["foo", "foo", "foo"]
[].init(60, 4);
// [60, 60, 60, 60]
[].init({}, 3);
// [{},{},{}]
[].init(true, 9);
// [true, true, true, true, true, true, true, true, true]
You can of course chain a .forEach()
after init()
.
(Actually, if you don't add this function to Array.prototype
, you can just use init()
, without the Array literal. That might be a "cleaner" solution)