137

While[] + []是一个空字符串,[] + {}is"[object Object]"{} + []is 0。为什么是{} + {}NaN?

> {} + {}
  NaN

我的问题不是为什么({} + {}).toString()"[object Object][object Object]"while NaN.toString(),这部分"NaN"这里已经有了答案

我的问题是为什么这只发生在客户端?在服务器端 ( Node.js ){} + {}"[object Object][object Object]".

> {} + {}
'[object Object][object Object]'

总结

在客户端:

 [] + []              // Returns ""
 [] + {}              // Returns "[object Object]"
 {} + []              // Returns 0
 {} + {}              // Returns NaN

 NaN.toString()       // Returns "NaN"
 ({} + {}).toString() // Returns "[object Object][object Object]"
 var a = {} + {};     // 'a' will be "[object Object][object Object]"

在 Node.js 中:

 [] + []   // Returns "" (like on the client)
 [] + {}   // Returns "[object Object]" (like on the client)
 {} + []   // Returns "[object Object]" (not like on the client)
 {} + {}   // Returns "[object Object][object Object]" (not like on the client)
4

1 回答 1

133

更新说明:这已在 Chrome 49 中修复

非常有趣的问题!让我们深入挖掘。

根本原因

差异的根源在于 Node.js 评估这些语句的方式与 Chrome 开发工具的方式。

Node.js 做了什么

Node.js 为此使用repl模块。

从 Node.js REPL 源代码

self.eval(
    '(' + evalCmd + ')',
    self.context,
    'repl',
    function (e, ret) {
        if (e && !isSyntaxError(e))
            return finish(e);
        if (typeof ret === 'function' && /^[\r\n\s]*function/.test(evalCmd) || e) {
            // Now as statement without parens.
            self.eval(evalCmd, self.context, 'repl', finish);
        }
        else {
            finish(null, ret);
        }
    }
);

这就像({}+{})在 Chrome 开发人员工具中运行一样,它也会"[object Object][object Object]"按您的预期生成。

chrome 开发者工具的作用

另一方面,Chrome 开发者工具执行以下操作

try {
    if (injectCommandLineAPI && inspectedWindow.console) {
        inspectedWindow.console._commandLineAPI = new CommandLineAPI(this._commandLineAPIImpl, isEvalOnCallFrame ? object : null);
        expression = "with ((window && window.console && window.console._commandLineAPI) || {}) {\n" + expression + "\n}";
    }
    var result = evalFunction.call(object, expression);
    if (objectGroup === "console")
        this._lastResult = result;
    return result;
}
finally {
    if (injectCommandLineAPI && inspectedWindow.console)
        delete inspectedWindow.console._commandLineAPI;
}

所以基本上,它call使用表达式对对象执行 a 。表达式为:

with ((window && window.console && window.console._commandLineAPI) || {}) {
    {}+{};// <-- This is your code
}

因此,如您所见,表达式是直接计算的,没有括号。

为什么 Node.js 行为不同

Node.js 的源代码证明了这一点:

// This catches '{a : 1}' properly.

Node 并不总是这样。这是更改它的实际提交。Ryan 对更改留下了以下评论:“改进 REPL 命令的评估方式”,并举例说明了不同之处。


犀牛

更新 - OP 对Rhino的行为方式很感兴趣(以及为什么它的行为类似于 Chrome devtools 而与 nodejs 不同)。

Rhino 使用完全不同的 JS 引擎,这与 Chrome 开发者工具和 Node.js 的 REPL 都使用 V8 不同。

这是在 Rhino shell 中使用 Rhino 评估 JavaScript 命令时发生的基本管道。

基本上:

Script script = cx.compileString(scriptText, "<command>", 1, null);
if (script != null) {
    script.exec(cx, getShellScope()); // <- just an eval
}

在这三个中,Rhino 的外壳是最接近实际的外壳,eval没有任何包装。Rhino's 是最接近实际eval()陈述的,您可以期望它的行为与预期完全一样eval

于 2013-06-24T06:39:05.333 回答