這是一道在StackOverflow上看到的面試題,內容主要爲:
JavaScript如何讓(a ==1 && a== 2 && a==3)的值爲true。
StackOverflow上的幾個答案:
重寫Object的toString或者valueOf
const a = {
i: 1,
toString: function () {
return a.i++;
}
}
if(a == 1 && a == 2 && a == 3) {
console.log('Hello World!');
}
Object類型與Number類型的==比較,Object類型會轉換爲數字類型後再和數字比較。
A爲Object類型,B爲Number類型,A==B實際是
ToPrimitive(A) == B
ToPrimitive(A)會嘗試調用A.toString()和A.valueOf()方法來獲取A對應的數字基本類型。
定義"a"屬性,並重寫它的getter方法
const value = function* () {
let i = 0;
while(true) yield ++i;
}();
Object.defineProperty(this, 'a', {
get() {
return value.next().value;
}
});
if (a === 1 && a === 2 && a === 3) {
console.log('yo!');
}
Object.defineProperty()定義"a"爲this的屬性,並定義了a屬性的getter方法。這樣在條件語句裏使用的a,實際爲this的屬性a。
這裏使用了ES6新增的特性:Generator函數來產生value。
字符編碼
有很好幾個答案都是利用了Unicode的字符編碼:同義字和隱形字符。
同義字示例
var aᅠ = 1;
var a = 2;
var ᅠa = 3;
if(aᅠ==1 && a== 2 &&ᅠa==3) {
console.log("Why hello there!")
}
隱形字符
var a = 1;
var a = 2;
var a = 3;
console.log(a == 1 && a == 2 && a == 3);
/****
var a = 1;
var a\u200c = 2;
var a\u200d = 3;
console.log(a == 1 && a\u200c == 2 && a\u200d == 3);
****/
數組toString隱含調用join()方法
a = [1,2,3];
a.join = a.shift;
console.log(a == 1 && a == 2 && a == 3);
這方法沒有重寫getter和toString/valueOf,它利用了數組的toString會隱含調用Array.join方法。
更詳細查看StackOverflow問題:https://stackoverflow.com/questions/48270127/can-a-1-a-2-a-3-ever-evaluate-to-true
版權聲明:著作權歸作者所有。