我被问到一个 JavaScript 面试问题:
如果
面试官告诉我,只有一种可能的数据类型会得出这个结果。
如果
x!=x
为 TRUE
,x
可能的类型是什么?面试官告诉我,只有一种可能的数据类型会得出这个结果。
x!=x
为 TRUE
,x
可能的类型是什么?如果
x!=x
为true
,x
可能是什么类型?
假设x
是一个变量,则此问题的答案是:
"number"
唯一符合此要求的值是NaN
,它永远不等于自己。
正如你所看到的,NaN
的类型是"number"
:
typeof NaN === "number"
。
如果x
仅仅是代表任何事情,函数和对象或数组文本也可以使用:
(function(){}) != (function(){})
({}) != ({})
[] != []
x
可以是一个getter,则有各种疯狂的选项: x
可以是一个getter,那么就有各种疯狂的选项:// Type == "string"
Object.defineProperty(window, 'x', {
get: function() { return String.fromCharCode(Math.random() * 0xFFFF | 0); }
});
// Type == "boolean"
Object.defineProperty(window, 'x', {
get: function() { return !(Math.random() * 2 | 0); }
});
// Type == "function"
Object.defineProperty(window, 'x', {
get: function() { return function() {}; }
});
// Type == "object"
Object.defineProperty(window, 'x', {
get: function() { return ({}); }
});
// Type == "object"
Object.defineProperty(window, 'x', {
get: function() { return []; }
});
使用 with
:
var o = {};
Object.defineProperty(o, 'x', {
get: function() { return []; } // any of the above types
});
with(o){
alert(x != x);
}
(感谢@Paul S.)
with
语句。 - Paul S.with
语句? - Cerbrusvar o = {}
,然后在 o
上用 defineProperty
定义了 _x_,再在 with (o) {x != x;}
中使用,那么你就不再需要全局对象。 - Paul S.
Object.defineProperty(window, 'x', {get: function () {return Math.random();}})
- Paul S.Object.defineProperty(window, 'x', {get: function () {return String.fromCharCode(Math.random() * 0xFFFF | 0);}})
,_布尔值_,Object.defineProperty(window, 'x', {get: function () {return !(Math.random() * 2 | 0);}})
,_函数_,Object.defineProperty(window, 'x', {get: function () {return function () {};}})
。 - Paul S.