16

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.

user694733
  • 15,208
  • 2
  • 42
  • 68
  • Compare using `==` so no type check will be included – Justinas Jun 06 '14 at 08:39
  • 1
    Simplicity is not the case here. You should use regular `for` loop for iterating arrays. – VisioN Jun 06 '14 at 08:39
  • 1
    I'm just wondering if you know what kind of data is stored in `i` and why is a String – Pablo Lozano Jun 06 '14 at 08:41
  • [*Simply* don't use `for…in` enumerations on arrays!](https://stackoverflow.com/q/500504/1048572) Just because a hammer is a simpler tool than an electric screwdriver, you shouldn't use it for screws. – Bergi Nov 10 '16 at 00:15
  • Ruined 72 hours of my time for this!!! – jeffbRTC Feb 24 '21 at 14:41
  • I agree with Bergi, but I think Javascript should fix the behavior of for(...in) for arrays since its behavior right now is pathological. You can use `for(const index of arr.keys()) {}` as a drop-in replacement in the meantime, as this is friendly for async code (unlike forEach). – podperson Aug 09 '21 at 21:31

5 Answers5

15

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.

0101
  • 2,697
  • 4
  • 26
  • 34
  • 2
    I did some reading, and I simply need to just stop using `for in` for arrays. It seems to be too easy to break unexpectedly. – user694733 Jun 06 '14 at 08:59
  • 1
    Exactly, I think that `forEach` is a good replacement. Simple and also faster solution than `for...i`. You should use `for...i` only if you need to iterate trough an object. – 0101 Jun 06 '14 at 09:04
  • forEach is not good if you're writing async code. The behavior of for...in for arrays is just stupid, it is NEVER what you want it to be. You can use for(const index of arr.keys()) {} as a drop-in replacement, but it seems to me that for...in should actually work properly. – podperson Aug 08 '21 at 22:55
  • Please use `parseInt` [_with_ the second parameter, `10`](/q/16880327/4642212). Consider using [`Number`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#Function_syntax) instead. – Sebastian Simon Sep 03 '21 at 08:24
3

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) {}
}
hsz
  • 148,279
  • 62
  • 259
  • 315
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.

megapctr
  • 931
  • 1
  • 7
  • 19
1

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

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
0

for-in loops properties in object, you could use for-of to loop array.

for (const i in [11, 22, 33, 44, 55]) {
    console.log(`${typeof i}: ${i}`);
}
string: 0
string: 1
string: 2
string: 3
string: 4

const obj = {
    11: 'a',
    22: 'b',
    33: 'c',
    44: 'd',
    55: 'e',
}
for (const i in obj) {
    console.log(`${typeof i}: ${i} -> ${obj[i]}`);
}
string: 11 -> a
string: 22 -> b
string: 33 -> c
string: 44 -> d
string: 55 -> e

for (const i of [11, 22, 33, 44, 55]) {
    console.log(`${typeof i}: ${i}`);
}
number: 11
number: 22
number: 33
number: 44
number: 55
Lawrence Ching
  • 423
  • 7
  • 16