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++){ if(isOdd(myArray[i])){ myArray.splice(i,1); i--; } }
The code above takes an array of arbitrary length and checks each value. If the value of an array bit satisfies an arbitrary condition (in this case, if it is odd), then it is deleted from the array.
Array.prototype.splice() used to remove the value from the array, and then i reduced to take into account the rest of the values in the "move down" array to fill in the gap that left the deleted value (so the loop does not skip the value).
However, the for loop ends when i is equal to the length of the array, which becomes shorter as values disappear.
Does the value of myArray.length dynamically decrease as the loop goes through or does it keep the value at the beginning of the loop and does not update as the values are deleted? If the last, what can I do to fix my cycle?
Thanks!
javascript arrays for-loop
snazzybouche
source share