Explain in vernacular: how to achieve a==1 && a==2 && a==3 as true

       I encountered this interesting interview question two days ago. I really wanted to break my head and didn't understand "how can a be equal to three numbers at the same time"?
       I finally realized the answer when I saw it. Although the answer is relatively abstract, today I will briefly explain a solution to this problem in my own words:

Before explaining this question, we first have to understand the JS grammar (day), fan (pit), that is:

  • Direct comparison (double equals comparison) if two value types are the same
  • If the two values ​​are not of the same type, the corresponding type conversion is performed according to object→string→number (boolean value→number) until the two values ​​are of the same type and then compared.

说白了就是JS的隐性转换!

Without further ado, let’s go to the picture directly:
insert image description here
Let’s do two experiments to verify:

  1. Object and Boolean Comparison
[] == true;  //false  

Arrays belong to objects and are implicitly converted to empty strings after encountering a double equals sign

  1. Object and String Comparison
[1,2,3] == '1,2,3' // true

Here the three arrays in the array are implicitly converted to '123' of the string, so they are equal!


OK! Understand the knowledge (heaven) knowledge (pit) of the above JS, then this problem is easily solved!

Let's first see what the answer is:

//实现a==1 && a==2 && a==3 为true
var a = {
    
    
    i : 1,
    toString(){
    
    
        return a.i++
    }
}
console.log(a==1 && a==2 && a==3 ) //true

【Thinking】:

  1. a becomes an object

  2. The object encounters a double equal sign ------> implicit conversion (the toString method on the object will be called)

    -------> Since "++" is after i, first return the value of i and then perform the ++ operation -------> can be true

In this way, a==1 && a==2 && a==3it can be true! !

In fact, the test point of this question is to examine the understanding of JS implicit conversion. If you think about it carefully, it is actually not difficult~~~

Guess you like

Origin blog.csdn.net/weixin_60297362/article/details/123037725