search

Home  >  Q&A  >  body text

javascript - [Quickly determine if the array is empty] []==false Why does it return true?

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?

習慣沉默習慣沉默2701 days ago1280

reply all(6)I'll reply

  • 黄舟

    黄舟2017-07-05 10:53:52

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

    reply
    0
  • typecho

    typecho2017-07-05 10:53:52

    http://tech.youzan.com/javasc...
    You will understand after reading it

    reply
    0
  • 大家讲道理

    大家讲道理2017-07-05 10:53:52

    Because they will be converted into Boolean values ​​for comparison,
    []==false
    =>
    true == false  //false

    reply
    0
  • 怪我咯

    怪我咯2017-07-05 10:53:52

    Convert to number 0 first, and then compare.

    reply
    0
  • 世界只因有你

    世界只因有你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!

    reply
    0
  • 滿天的星座

    滿天的星座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?

    reply
    0
  • Cancelreply