If an array is truthy in JavaScript, why doesn't it equal true?

后端 未结 3 1864
臣服心动
臣服心动 2020-12-19 12:00

I have the following code snippet:

if([]) {
  console.log(\"first is true\");
}

The console says first is true wh

3条回答
  •  不知归路
    2020-12-19 12:33

    You have force type coercion before making a Boolean equity check with the Object types.

    while "" == false // <- true or 0 == false // <- true works out well

    with the Object types it doesn't

    null == false // <- false
    

    so you better do like

    !!null === false // <- true or !![] === true // <- true

提交回复
热议问题