javaScript怎么满足条件输出 “OK” var a = ? if(a == 1 & a ==2 & a ==3) { console.

140 阅读1分钟

怎么满足条件输出 “OK”

 var a = ?   
 if(a == 1 & a ==2 & a ==3) {
     console.log("OK")
 }

答:方法一:

利用==号在比较数字和对象时会调用toString方法,然后重写toString方法

 a = {
    n: 0,
    toString:function() {
        return ++this.n
    }
}
if (a == 1 && a == 2 && a == 3) {
	console.log("通过!")
} else {
	console.log('不通过!')
}
// 通过

方法二:

也是重写toString方法,只是利用了数组了shift的特性

a = [1, 2, 3]
a.toString = a.shift
if (a == 1 && a == 2 && a == 3) {
  console.log("通过!")
} else {
	console.log('不通过!')
}
// 通过

方法三:

利用ES5新加的Object.defineProperty重写获取属性的get方法

var a, n = 0
Object.defineProperty(Window, "a", {
	get() {
		return ++n
	}
})
if (a == 1 && a == 2 && a == 3) {
	console.log("通过!")
} else {
	console.log('不通过!')
}
// 通过