Skip to content

a == 1 && a == 2 && a == 3 ​

2023-06-23 09:28:42

看见一个非常有意思的问题

ts
if (a == 1 && a == 2 && a == 3) {
  console.log('hello world')
}

乍一看好像是实现不了,不能让一个变量同时等于三个不同的值,但是我们这注意到这里是 ==而不是 ===,并且在 if 条件语句内,也就是说让这个判断最后范围 true 就可以了,那么就可以从一些其他的角度来解决。

toString 和 valueOf ​

首先我们可以通过隐式转换的 toString 方法,相当于重写了这个方法。

ts
const a = {
  val: 1,
  toString: () => {
    return a.val++
  }
}

if (a == 1 && a == 2 && a == 3) {
  console.log('hello world')
}

同理 valueOf 也是这样。

ts
const a = {
  val: 1,
  valueOf: () => {
    return a.val++
  }
}

if (a == 1 && a == 2 && a == 3) {
  console.log('hello world')
}

Object.defineProperty ​

把 a 定义到 window 上,再加上诸如 Object.defineProperty 的 api

ts
let tmp = 1
Object.defineProperty(window, 'a', {
  get: function () {
    return tmp++
  }
})

if (a == 1 && a == 2 && a == 3) {
  console.log('hello world')
}

with ​

ts
var i = 0

with ({
  get a() {
    return ++i
  }
}) {
  if (a == 1 && a == 2 && a == 3) {
    console.log('hello world')
  }
}

邪教 ​

以下有很多其他 歪门邪道的方法,都能实现

ts
const aᅠ = 1
const a = 2
const a = 3
if (a == 1 && a == 2 && a == 3) {
  console.log('hello world')
}
ts
var a = [1, 2, 3]
a.join = a.shift
if (a == 1 && a == 2 && ᅠa == 3) {
  console.log('hello world')
}
ts
let i = 0
let a = { [Symbol.toPrimitive]: () => ++i }

if (a == 1 && a == 2 && ᅠa == 3) {
  console.log('hello world')
}

链接 Stack Overflow

Released under the MIT License.