怎样使a==1&&a==2&&a==3=true成立

方法一,使用代理(对象的set,get)

let num = 1
Object.defineProperty(window,'a',{

  get(){
    return num++
  },

  set(){

  }
  
})

console.log(a==1&&a==2&&a==3)   // => true

方法二,利用js的隐式转换

如果是 == 两个等号,js会进行隐式转换
js在进行隐式转换的过程中,会调用toString和ValueOf方法(方法是对象原型链上的),向数字和字符串转化,所以,我们可以通过这两个方法,做一些手脚

  • 1.使用toString
let a = {
  num:1,
  toString(){
    return this.num++
  }
}

console.log(a==1&&a==2&&a==3)   // => true
  • 2.使用valueOf
let a = {
  num:1,
  valueOf(){
    return this.num++
  }
}

console.log(a==1&&a==2&&a==3)   // => true

需要注意的是,如果题目是 怎样使a=1&&a=2&&a===3=true成立, 那么就只能使用第一种方法了

原文地址:https://www.cnblogs.com/zoo-x/p/14845482.html