Why does !{}[true] evaluate to true in JavaScript?
{}[true]
is [true]
and ![true]
should be false
.
So why does !{}[true]
evaluate to true
?
I believe that's because plain {}[true]
is parsed as an empty statement block (not an object literal) followed by an array containing true
, which is true
.
On the other hand, applying the !
operator makes the parser interpret {}
as an object literal, so the following {}[true]
becomes a member access that returns undefined
, and !{}[true]
is indeed true
(as !undefined
is true
).
Because {}[true]
does not return true
, but undefined
, and undefined
is evaluated as false
:
http://jsfiddle.net/67GEu/
'use strict';
var b = {}[true];
alert(b); // undefined
b = !{}[true];
alert(b); // true
Because
{}[true]
evaluates to undefined
, and !undefined
is true
.
From @schlingel:
true
is used as key and {}
as hash map. There doesn't exist an property with the key true
so it returns undefined
. Not undefined
is true
, as expected.
Console session (Node.js [0.10.17]
):
> {}[true]
undefined
> !{}[true]
true
> [true]
[ true ]
> ![true]
false
>
However, in the Google Chrome console:
> !{}[true]
true
So, no inconsistencies. You're probably using an old version of the JavaScript VM. For those who need further evidence:
UPDATE
With Firefox, it also evaluates to true
:
上一篇: 什么是无值?