循环索引是字符串而不是整数

循环索引是字符串而不是整数

本文介绍了for(in)循环索引是字符串而不是整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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

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

有没有解决的办法?我可以将i显式转换为整数,但是这样做似乎无法使用更简单的for in而不是常规的for -loop达到目的.

Is there way around this? I could explicitly convert i to integer, but doing so seems to defeat the purpose using simpler for in instead of regular for-loop.

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

I am aware of using == in comparison, but that is not an option.

推荐答案

您有几种选择

  1. 转换为数字:

  1. Make conversion to a Number:

parseInt(i) === 1
~~i === 1
+i === 1

  • 不比较类型(使用==代替===):

  • Don't compare a type (Use == instead of ===):

    i == 1 // Just don't forget to add a comment there
    

  • 将for循环更改为(我会这样做,但这取决于您要实现的目标):

  • Change the for loop to (I would do this but it depends on what you are trying to achieve):

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

  • 通过这种方式,您不应该使用for...in遍历数组.请参阅文档: https://developer. mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...in

    By the way you should not use for...in to iterate through an array. See docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

    因为迭代的顺序取决于实现,所以进行迭代 数组上的元素可能无法以一致的顺序访问元素.所以 最好使用带有数字索引的for循环(或Array.forEach 或非标准for ... of循环)在数组上进行迭代时,其中 访问顺序很重要.

    Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the non-standard for...of loop) when iterating over arrays where the order of access is important.

    这篇关于for(in)循环索引是字符串而不是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-03 01:38