for(in)循环索引是字符串而不是整数 [英] for( in ) loop index is string instead of integer

查看:158
本文介绍了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..in不应用于遍历索引顺序为Array的数组 很重要数组索引只是具有可枚举的属性 整数名称,否则与一般Object相同 特性.无法保证for ... in将返回 以任何特定顺序索引,它将返回所有可枚举 属性,包括具有非整数名称的属性以及 继承.

    for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

    因为迭代的顺序取决于实现,所以进行迭代 数组上的元素可能无法以一致的顺序访问元素.所以 最好使用带有数字索引的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)循环索引是字符串而不是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆