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

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

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

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

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 18:28

    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).

提交回复
热议问题