I'm wondering if and what is a reliable and/or standard way of iterating an array whose length is changing inside the loop. I ask because I end up choosing a different method to do this each time I want to do it, e.g.
for ( var i = 0; i < myarray.length; i++ ) {
if (myarray[i] === 'something') {
myarray.splice(i, 1);
// *to avoid jumping over an element whose index was just shifted back to the current i
i--;
}
}
or
var i = 0;
while (myarray[i]) {
if (myarray[i] === 'something') {
myarray.splice(i, 1);
} else {
i++;
}
}
These are the ways I find myself doing this, but I'm curious if there is a standard approach.
I find simpler to iterate in the other direction :
for (var i=myarray.length; i--; ) {
if (myarray[i] === 'something') myarray.splice(i, 1);
}
This way you don't have to change the increment when removing.
Many developers, especially the ones who didn't deal with C-like languages before JavaScript, find it confusing to deal with the subtleties of the decrement operator. The loop I wrote can also be written as
for (var i=myarray.length-1; i>=0; i--) {
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