for( in ) loop index is string instead of integer
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) {}
}
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.
You have got several options
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
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.