在JavaScript中给出x!= x。 'x'的类型是什么? [英] Given x!=x in JavaScript. What is the type of 'x'?

查看:94
本文介绍了在JavaScript中给出x!= x。 'x'的类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript采访中被问过

I've been asked in a JavaScript interview


如果 x!= x TRUE x 的可能类型是什么?

If x!=x is TRUE, what is the possible type of x?

面试官告诉我, x 只有一种可能获得此结果的类型。

The interviewer told me there is only one possible type for x that gets this result.

推荐答案


如果 x!= x true x 的可能类型是什么?

If x!=x is true, what is the possible type of x?

假设 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆