Why if([]) is validated while [] == false in javascript?

前端 未结 3 2061
既然无缘
既然无缘 2020-12-01 21:22
if([] == false) alert(\'empty array is false\');
alert(+[]) // alert 0
if([]) alert(\'empty array is true\');

They both will run the alert

3条回答
  •  再見小時候
    2020-12-01 21:48

    There is a difference between evaluating a value as a boolean, and comparing it to true or false.

    Whe using the == operator, the values are converted so that the types correspond. The [] value converted to the empty string "", and converting that in turn to a boolean gives false, so [] == false becomes true.

    Evaluating [] as a boolean value will return true, because it is not a 'falsy' value, i.e. 0, false, null, "", NaN or undefined.

提交回复
热议问题