为什么!新的布尔值(false)在JavaScript中等于false? [英] Why does !new Boolean(false) equals false in JavaScript?

查看:144
本文介绍了为什么!新的布尔值(false)在JavaScript中等于false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自关于JavaScript类型的jQuery文档,这段代码描述了字符串的行为当转换为布尔值时(该话题与此问题无关,但它只是我找到代码的地方):

From the jQuery documentation on JavaScript types comes this snippet of code describing the behavior of strings when converted to booleans (that topic is not related to this question, but it's just where I found the code):

!"" // true
!"hello" // false
!"true" // false
!new Boolean(false) // false

我得到前三个例子,但我没有得到最后一个例子,因为:

I get the first three examples, but I don't get the last example, because:

new Boolean(false) == false //true
!false // true

所以我假设:

!new Boolean(false) // true

但是:

!new Boolean(false) // false, mind = blown

这是什么?甚至不...

What is this I don't even...

是因为:

new Boolean(false) === false // false

如果是这样,这个用途是什么目的?

If so, what purpose does this serve?

推荐答案

new Boolean(false)返回一个非空的对象。非null对象总是真实的。

new Boolean(false) returns an object which is not null. Non-null objects are always truthy.

因此,任何非null对象的将始终为false。

As a result, ! of any non-null object will always be false.

要向自己证明,可以在javascript控制台中运行

To prove it to yourself, you can run this in your javascript console

(typeof new Boolean(false))  //"object"

此外,您可以使用严格相等运算符来确认 new Boolean(false)实际上不是 false

Also, you can use the strict equality operator to confirm that new Boolean(false) isn't really false:

new Boolean(false) === false  // false

顺便提一下,将布尔函数作为函数调用 - 没有新 - 实际上确实返回一个原语

Incidentally, calling the Boolean function as a function—without the new—actually does return a primitive

!Boolean(false) // true

(typeof Boolean(false))  //"boolean"

这篇关于为什么!新的布尔值(false)在JavaScript中等于false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆