forEach() trouble when an element is removed during execution

Peter Michaux petermichaux at gmail.com
Sat Jun 16 23:04:13 PDT 2007


Hi,

I ran the following snip of code on Firefox 2 with Firebug installed.

var arr = [0,1,2,3];
arr.forEach(function(el) {
  console.log(el);
  if (el == 1) {
    arr.splice(el, 1);
  }
});

// output
// 0
// 1
// 3


Note that 2 is skipped yet 2 is in the array both before and after the
the forEach() execution.

I understand why this is happening if the underlying iterator is a for
loop  but iterators are supposed to hide implementation.

If I say I want to iterate over the elements of an array then I think
at least all the elements that are in the array both before and after
the iteration should be iterated.

Elements that are removed during the forEach execution but have not
yet been iterated...that is debatable if the removed elements should
be iterated. (In the case of DOM2 event handlers these would not be
iterated. Two browsers do it one way and two do it the other way.)

Elements that are added during the forEach execution, I think those
should not be iterated since that could lead to infinite loops.

So does forEach() behave properly in the above example? (I don't think so.)

Peter



More information about the Es4-discuss mailing list