我想知道为什么标题中给出的表达式
[] == ![]
被评估为 true
。
您不能将数组作为字符串进行比较。我明白了。如果
[] == []
将计算为 false,因为引用不同。虽然如果我们有以下声明。
var arr = [];
arr == arr // this evaluates to true simply because references are the same.
为了 A == B 返回 true
,A 和 B 必须为 false
或 true
。
A == !B 为了返回 true
A 可以是 true
而 B 可以是 false
反之亦然,但在这种情况下,A 和B 是相同的值,所以我不明白。
最佳答案
基本上,如果两种类型不同,Javascript 会尝试将两边都转换为 Number。如果它是一个对象,它会尝试转换成原始值
所以在这种情况下一步一步会是
=> []==![]
=> []==false // Type conversion by the statement itself
=> []==0 // To number of right operand
=> ""==0 // To Primitive call for Array which will in this case convert to empty string
=> 0==0 // To number call of "" which is 0
=> true
可以在编译器描述中查看 ecmascript 解释 http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
关于javascript - [] == ![] 计算结果为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38662231/