Lets see why JavaScript behaves like this. According to the ECMAScript standard specification for Array.prototype.forEach
,
when you delete an element at index 1, the element at index 2 becomes the element at index 1 and index 2 doesn’t exist for that object.
Now, JavaScript looks for element 2 in the object, which is not found, so it skips the function call.
That is why you see only a
and b
.
The actual way to do this, is to use Array.prototype.filter
var array = ["a", "b", "c"];
array = array.filter(function(currentChar) {
console.log(currentChar); // a, b, c on separate lines
return currentChar !== "b";
});
console.log(array); // [ 'a', 'c' ]