简体   繁体   中英

Array index does not respond to strict equality when using for…in loop

This is a strange behavior that I've encountered today. But I cannot understand why it happens.

for (let x in [1]) {
    console.log(x === 0) // false
    console.log(x == 0) // true
}

The code snippet should be self explanatory. On the first log we have strict equality and on the next one we have loose equality . Why are they returning different results? Aren't numbers of the same value equal no matter how we're comparing them?

PS: This problem doesn't exist if you're using array functions such as forEach() and map() for iteration

[1].forEach((_, i) => {
    console.log(i === 0) // true
    console.log(i == 0) // true
})

[1] is equivalent to {0: 1}

When you use for..in , it iterates through object's properties (keys). While keys are all in string, so it iterates through ['0']

So

'0' === 0 // false
'0' == 0 // true

could be easily understand since then

In this case, x is not a number because for... in iterates over object keys:

 for (let x in [1]) { console.log(typeof x); console.log(x === 0) // false console.log(x == 0) // true }

For arrays, you should be using for... of :

 for (let x of [1]) { console.log(typeof x); console.log(x === 0) // false console.log(x == 0) // false }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM