问题描述
来自,这段代码描述了字符串的行为当转换为布尔值时(该话题与此问题无关,但它只是我找到代码的地方):
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!