for( in ) loop index is string instead of integer

流过昼夜 提交于 2020-01-13 09:29:46

问题


Consider following code:

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

It will fail, because typeof i === 'string'.

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.

Edit:

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


回答1:


You have got several options

  1. Make conversion to a Number:

    parseInt(i) === 1
    ~~i === 1
    +i === 1
    
  2. Don't compare a type (Use == instead of ===):

    i == 1 // Just don't forget to add a comment there
    
  3. 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) { }
    }
    

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 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.

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.




回答2:


With === you compare also the type of values. Use == instead:

if ( i == 1 ) {}

or cast i to integer:

if ( +i === 1 ) {}

Also you can try with 'standard' for loop:

for (var i = 0; i < arr.length; i++) {
    if (i === 1) {}
}



回答3:


If you don't need browser support below IE9, you can use Array.forEach

If you do, use the good ol' for (i = 0; i < arr.length; i++) {} loop.




回答4:


Is this what you mean?

var arr = [1, 2, 3];
for(var i in arr) { //i is not the value of an element of the array, but its "attribute name"
    if(arr[i] === 1) {

    }
}

In any case, I'd use the good old classic for syntax, it's the recommended way to deal with arrays



来源:https://stackoverflow.com/questions/24077537/for-in-loop-index-is-string-instead-of-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!