为什么({} + {})=" [object Object] [object Object]"? [英] why ({}+{})="[object Object][object Object]"?

查看:142
本文介绍了为什么({} + {})=" [object Object] [object Object]"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试了代码:

{}+{} = NaN;
({}+{}) = "[object Object][object Object]";

为什么添加()更改结果?

推荐答案

{} + {} 阻止后跟一个表达式。第一个 {} 是块(就像你附加到 if 语句的那种), + {} 是表达式。第一个 {} 是一个块,因为当解析器查找语句并看到 {时,它会将其解释为一个街区的开放。那块空了,什么也没做。处理完块后,解析器会看到 + 并将其读作一元 + 。这将解析器转移到处理表达式。在表达式中, {启动对象初始值设定项而不是块,因此 {} 是对象初始值设定项。对象初始值设定项创建一个对象, + 然后尝试强制转换为一个数字,得到 NaN

{}+{} is a block followed by an expression. The first {} is the block (like the kind you attach to an if statement), the +{} is the expression. The first {} is a block because when the parser is looking for a statement and sees {, it interprets it as the opening of a block. That block, being empty, does nothing. Having processed the block, the parser sees the + and reads it as a unary +. That shifts the parser into handling an expression. In an expression, a { starts an object initializer instead of a block, so the {} is an object initializer. The object initializer creates an object, which + then tries to coerce to a number, getting NaN.

({} + {})中,开头转移解析器进入它期望表达式而不是语句的模式。所以()包含带有二进制<的两个对象初始值设定项/ em> + (例如,加法运算符,可以是算术或字符串连接)。二进制 + 运算符将尝试根据其操作数添加或连接。它将操作数强制转换为基元,在 {} 的情况下,它们每个都成为字符串[object Object]。所以你最终得到[object Object] [object Object],结果连接它们。

In ({}+{}), the opening ( shifts the parser into the mode where it's expecting an expression, not a statement. So the () contains two object initializers with a binary + (e.g., the "addition" operator, which can be arithmetic or string concatenation) between them. The binary + operator will attempt to add or concatenate depending on its operands. It coerces its operands to primitives, and in the case of {}, they each become the string "[object Object]". So you end up with "[object Object][object Object]", the result of concatenating them.

这篇关于为什么({} + {})=&quot; [object Object] [object Object]&quot;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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