1

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");
}

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

or for (var i = 0, listLength = list.length; i < listLength; i++) to save the constant recalculation of list.length.
2

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.