对象相加隐士转换规则(需要进行转换为原始类型)主要涉及到valueOf() 和toString()方法

 以上引用https://wangdoc.com/javascript/operators/arithmetic.html#%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%9B%B8%E5%8A%A0

 例如: 

const a = {
        valueOf() {
          return '1'
        },
        toString() {
          return false
        }
      }

      const b = {
        toString() {
          return true
        }
      }
      console.log(a + '1'); 
      console.log(b + true); 
      console.log(a + b); 
      console.log(a - b ); 

打印结果:

11
 2
1true
 0

猜你喜欢

转载自www.cnblogs.com/doumian/p/12671678.html