console.log([]==false); //输出为true
console.log(['1']==false);//输出为false
It can be seen that this can quickly determine whether the array is empty, but there are some doubts in the principle.
A known:
1. Equality operator "==": convert first and then compare. If one of the operands is a boolean, it is converted to a numeric value before comparing for equality. False is converted to 0 and true is converted to 1.
2. If one operand is an object and the other operand is not, call the valueOf() method of the object and use the obtained basic type value for conversion.
So the right side of []==fasle will be converted to 0. What about the left side? How is it converted?
黄舟2017-07-05 10:53:52
This is for you, a comparison table of javascript: Relational and Equality Operators
typecho2017-07-05 10:53:52
http://tech.youzan.com/javasc...
You will understand after reading it
大家讲道理2017-07-05 10:53:52
Because they will be converted into Boolean values for comparison,
[]==false
=>
true == false //false
世界只因有你2017-07-05 10:53:52
It makes sense to use this method to judge that the array is empty, right?
if([]){
alert('1111');
}
I thought it wouldn’t bounce, but it did. In most cases, it is still judged by length. Of course, length is also a pitfall when judging the number of elements!
滿天的星座2017-07-05 10:53:52
It can only be said that the internal mechanism of js is that an empty array is false, so false==false is true! Then the non-empty array is naturally converted into true, and true==false is not true! Is there anything difficult to understand?