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

后端 未结 3 1857
臣服心动
臣服心动 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:10

    This is strict equality. It meas that both operands should be the same thing. In the case of object, they should be exactly the same object. Comparison between object with the same structure and the same values will fail, they need to be reference to the same object to success.

    if([]===true){
      console.log("third is true");
    }
    

    In case of operands of different types, than the comparison between them becomes strict. This leads to the case above.

    if([]==true){
      console.log("second is true");
    }
    

    Also, in the first if statement, [] is automatically casted to boolean true.

提交回复
热议问题