snazzybouche snazzybouche - 3 months ago 5x
Javascript Question

When looping through values of a JS array, and I remove value, do I need to use while instead of for?

var myArray = [1,2,3,4,5,6,7,8,9];

function isOdd(value){
return value % 2;

for(var i = 0; i < myArray.length; i++){

The code above takes an array of arbitrary length and checks each value. If the value of the bit of the array meets an arbitrary condition (in this case if it is odd), then it is removed from the array.

is used to remove the value from the array, and then
is decremented to account for the rest of the values in the array "moving down" to fill in the gap that the removed value left (so the loop doesn't skip over a value).

However, the
loop ends when
equals the length of the array, which gets shorter as values are removed.

Does the value of
decrease dynamically as the loop proceeds, or does it save the value at the start of the loop and not update as values are removed? If the latter, what can I do to fix my loop?

Thank you!


myArray.length is changing with the operation on the array. But looping and splicing leads to unwanted results, if not proper padded.

To prevent unnecessary corrections, use a while loop from the end, to keep the rest of the array for processing.

function isOdd(value) {
    return value % 2;

var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9],
    i = myArray.length;

while (i--) {
    if (isOdd(myArray[i])) {
        myArray.splice(i, 1);