为什么在JavaScript中将{} [true]评估为true?
{}[true]是[true] , ![true]应该是false 。
那么为什么!{}[true]评估为true ?
我相信那是因为plain {}[true]被解析为一个空语句块(不是对象字面),后面跟着一个包含true的数组,这是true 。
另一方面,应用! 运算符使解析器将{}解释为对象字面值,因此以下{}[true]将成为返回undefined的成员访问,并且!{}[true]确实为true (如!undefined为true )。
由于{}[true]不返回true ,但undefined ,并且undefined被评估为false :
http://jsfiddle.net/67GEu/
'use strict';
var b = {}[true];
alert(b); // undefined
b = !{}[true];
alert(b); // true
因为
{}[true]
评估为undefined ,并且!undefined为true 。
来自@schlingel:
true用作键和{}作为哈希映射。 不存在关键字为true的属性,所以它返回undefined 。 正如预期的那样,不undefined是否为true 。
控制台会话(Node.js [0.10.17] ):
> {}[true]
undefined
> !{}[true]
true
> [true]
[ true ]
> ![true]
false
>
但是,在Google Chrome控制台中:
> !{}[true]
true
所以,没有不一致。 您可能正在使用旧版本的JavaScript VM。 对于需要进一步证据的人员:
UPDATE
随着Firefox,它也评估为true :
上一篇: Why does !{}[true] evaluate to true in JavaScript?
下一篇: JavaScript checking for null vs. undefined and difference between == and ===
