简体   繁体   English

为什么 Boolean([]) 在 JavaScript 中返回 true?

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

In JavaScript [] == 0 returns true, as expected.正如预期的那样,在 JavaScript [] == 0中返回 true。 But Boolean([]) also returns true.但是Boolean([])也返回 true。

I would expect it to return false, as == 0 checks for false.我希望它返回 false,因为== 0检查是否为 false。

It is simply just how the Boolean() function is implemented.这就是Boolean()函数的实现方式。

If you look at the MDN documentation for the Boolean() function you will find this (emphasis mine)如果您查看Boolean()函数的MDN 文档,您会发现这一点(强调我的)

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.如果该值被省略或为 0、-0、null、false、NaN、undefined 或空字符串 (""),则该对象的初始值为 false。 All other values, including any object, an empty array ([]), or the string "false", create an object with an initial value of true.所有其他值,包括任何对象、空数组 ([]) 或字符串“false”,都会创建一个初始值为 true 的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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