console.log([]==false); //输出为true console.log(['1']==false);//输出为false
It can be seen that this can quicklydetermine 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?
This is for you, a comparison table of javascript: Relational and Equality Operators
http://tech.youzan.com/javasc...
You will understand after reading it
Because they will be converted into Boolean values for comparison,
[]==false
=>
true == false //false
Convert to number 0 first, and then compare.
It makes sense to use this method to judge that the array is empty, right?
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!
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?