如果我在 Chrome 控制台中输入
{} + {}
我得到“[object Object][object Object]”
但是如果我添加分号,结果会有所不同:
{} + {};
我得到 NaN
虽然我不明白其中的区别。第一个是有道理的,对我来说是 addition operator rules如下:
- If at least one operand is an object, it is converted to a primitive value (string, number or boolean);
- After conversion, if at least one operand is string type, the second operand is converted to string and the concatenation is executed;
- In other case both operands are converted to numbers and arithmetic addition is executed.
由于两个操作数都是对象,因此它们都转换为字符串。 但第二种情况是怎么回事呢?
如果我在这两种情况下分配一个值(a = ...)
,我的变量将是一个字符串。我试图寻找给出表达式时 Chrome 控制台返回的规范,但没有找到。
奇怪的是,添加注释也会返回 NaN
:
{} + {}//注释
=> NaN
我知道 JavaScript 有时可能很奇怪,但几乎总是有一个合乎逻辑的解释。这里似乎取决于Chrome如何解释它。
另一方面,Firefox 对于这两种情况都返回 NaN
,我也不明白。
最佳答案
我认为差异在于 Chrome 控制台解释代码的方式:
这是一个表达式:
{} + {}
//=> "[object Object][object Object]"
这是一个“程序”:
{} + {};
请注意,如果这是您的“完整程序”,则只需使用 {} + {}
即可实现 NaN
:
以下是 Axel Rauschmayer 博士在 "What is {} + {} in JavaScript?" 中所说的话
The problem is that JavaScript interprets the first {} as an empty code block and ignores it. The NaN is therefore computed by evaluating +{} (plus followed by the second {}).
因此,在 {} + {};
中,NaN
来自评估 +{}
。 (第一个 {}
将被忽略。)
第一个 {}
作为代码块在此示例中更加明显:(在命令行中尝试此操作)
{ while (false) x++ } + {}
//=> NaN
如果 JS 将 { while (false) x++ }
视为对象,则会抛出语法错误。但事实并非如此,在这种情况下它必须是一个代码块;它会忽略它并计算 +{}
并产生 NaN
。
因此,要“强制”JS 将 {}
视为对象而不是代码块,您可以将它们包装在 () 中。在 Chrome 控制台中尝试一下:
({}) + ({});
//=> "[object Object][object Object]"
({} + {});
//=> "[object Object][object Object]"
关于javascript - 为什么 Chrome 控制台在 {} + {} 和 {} + {} 之间给出不同的结果;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62010047/