I've found that I can't use a for each loop on an empty array in javascript. Can anyone explain to me why this is?
I've initialized an array in javascript like so:
var arr = new Array(10);
when I use a for each loop on the array nothing happens:
arr.forEach(function(i) {
i = 0;
});
the result is still an array of undefined values:
arr = [ , , , , , , , , , ];
I think that maybe since each item in the array is undefined, it doesn't even execute the forEach. I would think that it would still iterate through the undefined items. Can anyone explain why this is occurring? This question is not asking how to most efficiently fill an array with zeros, it's asking details on the interaction of a for each loop and an empty array.
You can use a forEach like you intended if you modify the array initialization to be:
var arr = Array.apply(null, Array(10))
And then you can do a foreach like:
arr.forEach(function(el, index) {
arr[index] = 0;
});
The result is:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With