有人可以向我解释为什么...(这是在 chrome 控制台中)
空==假//假
!null == false //假
[] ? '你好' : '再见' //'你好'
[] == 真?'你好' : '再见' //'再见'
我可以想出更多,但基本上 javascript 是如何得出这些结果的?
有人可以向我解释为什么...(这是在 chrome 控制台中)
空==假//假
!null == false //假
[] ? '你好' : '再见' //'你好'
[] == 真?'你好' : '再见' //'再见'
我可以想出更多,但基本上 javascript 是如何得出这些结果的?
JavaScript 做了很多类型转换,这在不知道的情况下并不明显(JavaScript 相等传递性很奇怪)。
!NOT 运算符、函数Boolean、? :三元运算符、if- 子句和逻辑 AND/OR 运算符确实使用内部ToBoolean转换- 它是我们对假值0、NaN、""、null和的理解undefined的原因false。
但是,当您比较事物时,(非严格)相等比较算法开始发挥作用,在比较对角线类型时会产生一些看似奇怪的结果。在你的情况下:
magic *waves hands mysteriously*
On a more serious note, for the first two, the ! operator calls toBoolean on null, so if you checked !null == !false or !!null == false you should get true. Similar things are likely happening in the other cases.
With information provided by Tore Hanssen, we can answer the other two as well. [] is a 'truthy' value, but not a boolean, so directly comparing it to true returns false. However, you could use the ! operator again to make it a boolean, so !![] == true returns true!
这里有一篇关于这个主题的有趣帖子:http: //javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/
在您的某些示例中,要强制强制,仅使用“==”是不够的。
!!null == 假
!![]
!![] == 真