For (in) loop index is a string instead of an integer

Consider the following code:

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

It will not succeed because typeof i === 'string'.

Is there any way around this? I could explicitly convert ito integer, but it seems to defeat the target using a simpler for ininstead of the usual for-loop.

Edit:

I know the use ==for comparison, but this is not an option.

+4
source share
4 answers

You have several options.

  • Make a conversion to number:

    parseInt(i) === 1
    ~~i === 1
    +i === 1
    
  • Do not compare type (use ==instead ===):

    i == 1 // Just don't forget to add a comment there
    
  • 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/en-US/docs/Web/JavaScript/Reference/Statements/for...in

for..in , . - . , ... , , , .

, . for ( Array.forEach ... ) , .

+5

=== . ==:

if ( i == 1 ) {}

i :

if ( +i === 1 ) {}

'standard' for:

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

IE9, Array.forEach

, good ol for (i = 0; i < arr.length; i++) {}.

+3

, ?

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) {

    }
}

, for,

+1
source

Source: https://habr.com/ru/post/1543519/


All Articles