在JavaScript中给出x!= x.'x'的类型是什么?

sun*_*kgp 2 javascript

我在JavaScript采访中被问过

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

面试官告诉我,只有一种可能的类型x可以得到这个结果.

Que*_*tin 13

值为NaN,其类型为Number.

从比较平等的规范:

如果x是NaN,则返回false.

NaN 永远不等于任何东西,包括它自己.


Cer*_*rus 11

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

假设这x是一个变量,这个问题的答案是:

"number"
Run Code Online (Sandbox Code Playgroud)

满足此要求的唯一NaN,它永远不等于自身.

正如你所看到的,类型NaN"number":
typeof NaN === "number".


如果x仅仅是任何东西的占位符,函数和对象或数组文字也可以工作:

(function(){}) != (function(){})
({}) != ({})
[] != []
Run Code Online (Sandbox Code Playgroud)

如果x可以成为一个吸气者,那么有各种各样的疯狂选择:

// 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 []; }
});
Run Code Online (Sandbox Code Playgroud)

使用with:

var o = {};
Object.defineProperty(o, 'x', {
  get: function() { return []; } // any of the above types
});

with(o){
  alert(x != x);
}
Run Code Online (Sandbox Code Playgroud)

(感谢@Paul S.)