简体   繁体   English

需要说明:在JavaScript中使用... in和for(;;)时的输出不同

[英]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. 在NodeJS中,我创建了以下两个脚本,它们都旨在从数组中删除偶数。

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: 在第二个脚本中,我将for..in循环更改为for(;;)循环,如下所示:

#!/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. 虽然我的意图是相同的,但两个for循环给了我不同的输出。 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. 我发现,在我的第一个脚本中,如果原始数组中存在两个相邻的偶数, if条件似乎仅应用于跳过第二个偶数的第一个偶数。 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 ). 你的for...in循环只会执行7次迭代,因为当数组仍在迭代时,你的4个键是从数组中拼接出来的,而你的for(;;)循环将总是执行所有11次迭代,因为这是在开头定义( 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. 作为结束注释,您不应该使用for...in循环来迭代数组。 This answer details why this is a bad idea. 这个答案详述了为什么这是一个坏主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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