Why does !{}[true] evaluate to true in JavaScript?

前端 未结 10 1476
一个人的身影
一个人的身影 2020-12-12 17:55

{}[true] is [true] and ![true] should be false.

So why does !{}[true] evaluate to true

10条回答
  •  一个人的身影
    2020-12-12 18:28

    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:

    Enter image description here

    UPDATE

    With Firefox, it also evaluates to true:

    Enter image description here

提交回复
热议问题