简体   繁体   中英

Why does Boolean([]) return true in JavaScript?

In JavaScript [] == 0 returns true, as expected. But Boolean([]) also returns true.

I would expect it to return false, as == 0 checks for false.

It is simply just how the Boolean() function is implemented.

If you look at the MDN documentation for the Boolean() function you will find this (emphasis mine)

The value passed as the first parameter is converted to a boolean value, if necessary. If the value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. All other values, including any object, an empty array ([]), or the string "false", create an object with an initial value of 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