javascript gotcha: empty list to boolean conversio

2020-07-02 22:18发布

Why both

 [] == false

and

![] == false

are true?

标签: javascript
3条回答
走好不送
2楼-- · 2020-07-02 22:42

An empty list, [] must be considered a "falsey", however in ![] the ! is then converting the operation to check for an object reference, where a non-null is not considered a "falsey".

查看更多
够拽才男人
3楼-- · 2020-07-02 22:52

Before [] is compared to false, it is coerced to a string which is coerced to a number, the empty string in the case of the empty array. The empty string coerces to 0 which is the same value that false coerces to numerically.

Use === instead of == to avoid this problem

These other arrays are also falsey:

  ['']
  [[[]]]
  (function () { var arr = []; arr[0] = arr; })()
  [0]
  ['-0.0']
查看更多
够拽才男人
4楼-- · 2020-07-02 22:59

The === operator is your friend. Never use the == operator; it will bite you, as you can see.

查看更多
登录 后发表回答