在JavaScript中给出x!= x。 'x'的类型是什么? [英] Given x!=x in JavaScript. What is the type of 'x'?
问题描述
我在JavaScript采访中被问过
I've been asked in a JavaScript interview
如果
x!= x
是TRUE
,x
的可能类型是什么?
If
x!=x
isTRUE
, what is the possible type ofx
?
面试官告诉我, x
只有一种可能获得此结果的类型。
The interviewer told me there is only one possible type for x
that gets this result.
推荐答案
如果
x!= x
是true
,x
的可能类型是什么?
If
x!=x
istrue
, what is the possible type ofx
?
假设 x
是一个变量,这个问题的答案是:
Assuming that x
is meant to be a variable, the answer to this question is:
"number"
满足的唯一值这个要求是 NaN
,它永远不等于自己。
The only value that satisfies this requirement is NaN
, which never equals itself.
如您所见, NaN
的类型为number
:
typeof NaN ===number
。
如果 x
仅仅是任何,函数和对象的占位符或者数组文字也可以工作:
If x
is merely a placeholder for anything, functions and object or array literals would work, too:
(function(){}) != (function(){})
({}) != ({})
[] != []
如果 x
可以是一个吸气者,那么还有各种各样的疯狂选择:
If x
can be a getter, then there's all sorts of crazy options:
// 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 []; }
});
将与
一起使用:
var o = {};
Object.defineProperty(o, 'x', {
get: function() { return []; } // any of the above types
});
with(o){
alert(x != x);
}
(感谢 @Paul S。)
这篇关于在JavaScript中给出x!= x。 'x'的类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!