javascript - [Quickly determine if the array is empty] []==false Why does it return true?
習慣沉默
習慣沉默 2017-07-05 10:51:52
0
6
1270
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?

習慣沉默
習慣沉默

reply all(6)
黄舟

This is for you, a comparison table of javascript: Relational and Equality Operators

typecho

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?

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!

滿天的星座

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?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!