for(in)循环索引是字符串而不是整数

use*_*733 5 javascript for-loop

考虑以下代码:

var arr = [111, 222, 333];
for(var i in arr) {
    if(i === 1) {
        // Never executed
    }
}
Run Code Online (Sandbox Code Playgroud)

它会失败,因为typeof i === 'string'.

这有什么办法吗?我可以显式转换i为整数,但这样做似乎使用simpler for in而不是regular for-loop来破坏目的.

编辑:

我知道==比较使用,但这不是一个选择.

010*_*101 9

你有几个选择

  1. 转换为数字:

    parseInt(i) === 1
    ~~i === 1
    +i === 1
    
    Run Code Online (Sandbox Code Playgroud)
  2. 不要比较类型(使用==而不是===):

    i == 1 // Just don't forget to add a comment there
    
    Run Code Online (Sandbox Code Playgroud)
  3. 将for循环更改为(我会这样做,但这取决于您要实现的目标):

    for (var i = 0; i < arr.length; i++) {
       if (i === 1) { }
    }
    
    // or
    
    arr.forEach(function(item, i) {
       if (i === 1) { }
    }
    
    Run Code Online (Sandbox Code Playgroud)

顺便说一句,你不应该使用for...in迭代数组.请参阅docs:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

for..in不应该用于迭代索引顺序很重要的数组.数组索引只是具有整数名称的可枚举属性,并且与一般对象属性相同.无法保证for ... in将以任何特定顺序返回索引,并且它将返回所有可枚举属性,包括具有非整数名称和继承的属性.

因为迭代的顺序是依赖于实现的,所以迭代数组可能不会以一致的顺序访问元素.因此,在迭代访问顺序很重要的数组时,最好使用带有数字索引的for循环(或者Array.forEach或非循环的for-standard).

  • 我读了一些书,我只需要停止对数组使用“for in”即可。似乎太容易被意外打破了。 (2认同)

归档时间:

查看次数:

3441 次

最近记录:

8 年,5 月 前