简体   繁体   中英

Explaination needed: Different outputs when used for…in and for(;;) in JavaScript

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.

What you're doing is wrong. You're removing keys from the array whilst looping through the same array. Your for...in loop will only ever perform 7 iterations, as 4 of your keys are spliced from the array whilst the array is still being iterated through, whereas your for(;;) loop will always perform all 11 iterations as this is defined at the beginning ( myarr.length ).

You should define a second array to use for your results instead:

for...in

var myarr = [2,3,5,1,6,2,28,5,7,90,3],
    resultarr = [];
console.log(myarr);
for(var i in myarr){
    if(myarr[i] % 2 != 0){
        resultarr.push(myarr[i])
    }
}
console.log(resultarr);
-> [3, 5, 1, 5, 7, 3]

for(;;)

var myarr = [2,3,5,1,6,2,28,5,7,90,3],
    resultarr = [];
console.log(myarr);
for(var i=0;i<myarr.length;i++){
    if(myarr[i] % 2 != 0){
        resultarr.push(myarr[i]);
    }
}
console.log(resultarr);
-> [3, 5, 1, 5, 7, 3]

As an ending note, you shouldn't use the for...in loop for iterating through arrays anyway. This answer details why this is a bad idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM