2

An array with uninitialized values e.g. new Array(100) doesn't iterate with forEach. The length is correct. Creating an array with [undefined,undefined,...] iterates as expected but creating an array with [,,,,,] doesn't.

I'm wondering if someone can explain this to me.

var array = new Array(100),
    msg;

_init();

console.log("Array length:",array.length);

// forEach is skipped
a = ["forEach:"];
(array).forEach(function(i){
  a.push(i);
});
console.log(a.join(','));


// forEach is also skipped
a = ["forEach array without undefined:"];
([,,,]).forEach(function(i){
  a.push(i);
});
console.log(a.join(','));

// forEach is displayed
a = ["forEach normal array:"];
([undefined,undefined,undefined,undefined]).forEach(function(v,i){
  a.push(v);
});
console.log(a.join(','));

// for is displayed
a = ["for:"]
for(var i=0;i<array.length;i++){
  a.push(i);
}
console.log(a.join(','));

// array.join is displayed (even the ough the values are empty)
a = ["join:"]
a = a.concat(array)
console.log(a.join(','));

// log to target div (ignore this)
function _init(){
  console = {log:targetlog};
}
function targetlog(){
  var args = Array.prototype.slice.apply(arguments);
  $("#target").append("<div>" + args.join(" ") + "</div>")
}
span {
  outline:1px solid gainsboro;
  margin:2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target"></div>
Shanimal
  • 11,517
  • 7
  • 63
  • 76

1 Answers1

2

I'm wondering if someone can explain this to me.

That is the spec.

forEach and its brethren ignore "holes" in sparse arrays. For more information, see this blog post.

From MDN:

forEach() executes the provided callback once for each element present in the array

The spec says the same thing.

  • Array.apply(null, Array(3)) is exactly what i was looking for. Thanks! – Shanimal Apr 16 '16 at 06:39
  • 1
    If you want to fill in the holes, `Array(3).fill()` will also work if you have `Array#fill` available. –  Apr 16 '16 at 06:41
  • Im using an older version of node. It doesn't seem to be there. :( – Shanimal Apr 16 '16 at 06:46
  • fwiw, I voted to reopen the question (in error) attempting to see the duplicate question. Didn't see the banner at the top because it was above the fold. I did search for the question but didn't find anything. Thanks for the answer anyway. The blog is great. It makes perfect sense considering deletion of elements. – Shanimal Apr 16 '16 at 06:56