简体   繁体   中英

why does “[] == 0” return true while “[]” is true and “0” is false?

If i execute the following lines in thw browser console

!![] //--- returns true
!!0 //--- returns false

I get that [] and 0 have different boolean values.

I don't understand why

[] == 0 //--- returns true

returns true .

What am I missing?

Remember that array is object and 0 is number.

And as "user2864740" told..

1) When you doing

!![] //--- returns true
!!0 //--- returns false

You are performing so called "ToBoolean" convertion

https://es5.github.io/#x9.2

Number

The result is false if the argument is +0, −0, or NaN; otherwise the result is true.

Object ( our [] )

always true

2) But when you using == you performing so called "Equality Comparison"

https://es5.github.io/#x11.9.3

Here thins a little bit complicated but to understand what happens you have to remember that == do a type coercion ( so you can compare oranges to apples :) )

First of all compiler converts [] to some primitive type.

If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).

How ToPrimitive works is a matter of an article :), but's it easy to remember that closet primitive type to array is string. Array will be converted to empty string.

[].toString() === ""

So now we need to compare empty string and number 0

"" == 0   // true

Hmmm. So it's true. But why is that? Remember that when you compare with "Equality Comparison" number and string

  1. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

So let's try to convert empty string to number

Number("") === 0

And in the end

0 === 0

I hope that's explains something :)

JavaScript可能会将数组转换为数字:
!!Number([]) // false
Number([]) == 0 // true

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