A few steps to let you remember the operation and conversion rules of the equal sign operator in JS

Compare according to the rules from top to bottom until the exact result can be obtained

  1. Both ends are of the same type, compare values

    If it is an object, compare the address of the object with the object

  2. As long as there are NaNs at both ends of the equal sign, return false

    NaN == [] , NaN == null , NaN == 0 , NaN == NaN ,'a' == NaN is false

  3. When undefined and null appear at both ends, it will return true only when comparing itself with itself, or comparing the two with each other, and false at other times

    null == undefined which is true, null == [], null == 'null' which is false

  4. Both ends are primitive types, converted to numeric comparisons

    true == 1, which is true, because +true turns into a number of 1, 'a' == 1, which is false, because +'a' is NaN, and jumps to the second step, so it is false

  5. One end is the original type, and the other end is the object type. After converting the object to the original type, enter step 1

    So how does an object convert to a primitive type?

    1. If the object has [Symbol.toPrimitive]a method, call that method.
      If the method can get the original value, use the original value;
      if it can’t get the original value, throw an exception, then use the next method

      const a = {
              
              
        [Symbol.toPrimitive](){
              
              
            console.log('toPrimitive')
            return 1;//得到原始值,如果return this,就得不到原始值,会报错
        }
      };
      if (a == 1 && a == 2 && a == 3) {
              
              
        console.log('你好');
      }
      
    2. Call valueOfthe method of the object, the object has this method, because there is an Object on the prototype chain, and the Object has this valueOf method

      If the method can get the original value, use the original value;
      if not, go to the next step

    3. call toStringthe method of the object

      If the method can get the original value, use the original value;
      if not, throw an exception

// 如何让判断成立输出'你好'
if (a == 1 && a == 2 && a == 3) {
    
    
  console.log('你好');
}
//答案:
const a = {
    
    
  count: 1,
  valueOf() {
    
    
    console.log('valueOf');//会打印三次valueOf
    return this.count++;
  },
};
if (a == 1 && a == 2 && a == 3) {
    
    
  console.log('你好');
}

Guess you like

Origin blog.csdn.net/qq_53461589/article/details/131020310