【问题标题】:Given x!=x in JavaScript. What is the type of 'x'? [duplicate]在 JavaScript 中给定 x!=x。 “x”的类型是什么? [复制]
【发布时间】:2015-09-08 11:41:57
【问题描述】:

我在 JavaScript 面试中被问到

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

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

【问题讨论】:

  • Object.defineProperty(window, 'x', {get: function () {return Math.random();}})
  • 下一个面试问题:对以下destroyallsoftware.com/talks/wat进行代码审查
  • @Cerbrus 问题提到 types 让我们再填写几个,StringObject.defineProperty(window, 'x', {get: function () {return String.fromCharCode(Math.random() * 0xFFFF | 0);}})Bool , Object.defineProperty(window, 'x', {get: function () {return !(Math.random() * 2 | 0);}}), 函数 Object.defineProperty(window, 'x', {get: function () {return function () {};}})

标签: javascript


【解决方案1】:

值为NaN,其类型为Number。

来自the spec 比较相等:

如果 x 为 NaN,则返回 false。

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

【讨论】:

    【解决方案2】:

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

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

    "number"
    

    满足此要求的唯一NaN,它永远不会等于它自己。

    如您所见,NaN类型"number":
    typeof NaN === "number"


    如果x 只是任何东西的占位符,那么函数和对象或数组字面量也可以工作:

    (function(){}) != (function(){})
    ({}) != ({})
    [] != []
    

    如果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 []; }
    });
    

    使用with:

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

    (感谢@Paul S.

    【讨论】:

    • 请随意在此答案中包含我的 cmets 中的代码。您还可以提及with 声明
    • with 声明?
    • 如果你有var o = {},然后是defineProperty x on o,然后是with (o) {x != x;},你就不再需要全局对象了
    • @PaulS.: 太棒了!添加:D
    猜你喜欢
    • 2013-08-17
    • 1970-01-01
    • 2019-03-27
    • 2023-03-04
    • 2013-01-30
    • 2014-02-11
    • 2013-08-29
    • 1970-01-01
    • 2011-01-07
    相关资源
    最近更新 更多