Question

Why is the condition never satisfied? It never produces a popup which in my understanding should show once x is the 3rd element of the list.

var list = [];
list[0] = "ahhah";
list[1] = "abcdef";
list[2] = "123";

for (var x in list) { 
   if (x == "123")
     alert("HA");
}
Was it helpful?

Solution

When you iterate an array with for..in, you will get the indexes, in string format. You should use normal loop, like this

for (var i = 0; i < list.length; i += 1) {
   if (list[i] == "123")
     alert("HA");
}

Quoting from for..in MDN Documentation page,

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.

OTHER TIPS

for..in will populate x with the key - not the value. It's usually used for objects and not arrays.

for (var x in list) {
    //x = 0 / 1 / 2
    if (list[x] == "123")
        alert("HA");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top