In NodeJS, I created the following two scripts, both of them was intended to remove even numbers from an array.
This is my 1st script:
#!/usr/bin/nodejs
var myarr = [2,3,5,1,6,2,28,5,7,90,3];
console.log(myarr);
for(var i in myarr){
if(myarr[i] % 2 == 0){
myarr.splice(i,1);
--i;
}
}
console.log(myarr);
Output for the first script was following:
[ 2, 3, 5, 1, 6, 2, 28, 5, 7, 90, 3 ]
[ 3, 5, 1, 2, 5, 7, 3 ]
In 2nd script, I changed for..in
loop to for(;;)
loop as follows:
#!/usr/bin/nodejs
var myarr = [2,3,5,1,6,2,28,5,7,90,3];
console.log(myarr);
for(var i=0;i<myarr.length;i++){
if(myarr[i] % 2 == 0){
myarr.splice(i,1);
--i;
}
}
console.log(myarr);
I got following output for the 2nd script:
[ 2, 3, 5, 1, 6, 2, 28, 5, 7, 90, 3 ]
[ 3, 5, 1, 5, 7, 3 ]
Although my intention was the same, two for loops gave me different outputs. I figured out that, in my first script, if there are two adjacent even numbers exist in the original array, if
condition seems to be applied for the first even number only where the second even number is skipped. I would really appreciate if anybody can explain this difference clearly.