6

topic:

    if (a == 1 && a == 2 & a == 3) {
      console.log(1);
    }

Under what circumstances will output 1?

analysis

When judging the double equal sign, the problem of type conversion is designed. If the numeric types on both sides of the equal sign are not the same, you can try to convert them into a type. When the object type uses the double equal sign, implicit conversion will be involved. When a==1 is executed, the Valueof method will be called first for judgment. If it fails, it will continue to call toString(), and then convert the string returned by toString into a number. The type continues to be compared with a. The priority of the ValueOf method will be higher when the == sign is used, and the toSrting method will be judged every time the == sign is used. This is the solution when a is the object. You can also use the defineProperty method of Object. First, declare a as a global variable, then a is a property in the window. Use this method to monitor a and solve this problem.

Solution one:

Use the valueOf method of the object attribute to increase a after the comparison is performed once

    var a = {
      i: 1,
      valueOf: () => {
        return a.i++
      }
    }

Solution two:

Use the toString() method of the object property to increase a after the comparison is performed once

    var a = {
      i: 1,
      toString:() =>{
        return a.i++
      }
    }

Solution three

Use the Object.defineProperty method to monitor the a property in the window object, and call the get method when obtaining a

    var a = 0
    Object.defineProperty(window,"a",{
      get(){
        return ++a
      }
    })

If it helps, please like it~


我的名字豌豆
406 声望746 粉丝

一起共同进步吧!