gpt4 book ai didi

javascript - 为什么括号中的加号运算符的工作方式不同?

转载 作者:行者123 更新时间:2023-12-02 15:55:28 27 4
gpt4 key购买 nike

您能解释一下为什么结果不同吗?

  1. ({} + {})//= "[object Object][object Object]"
  2. {} + {}//= NaN

我知道在这两种情况下对象都会转换为字符串,但为什么在第二种情况下结果会转换为数字?

最佳答案

来自:

http://www.2ality.com/2012/01/object-plus-object.html

The problem is that JavaScript interprets the first {} as an emptycode block and ignores it. The NaN is therefore computed by evaluating+{} (plus followed by the second {}). The plus you see here is not the binary addition operator, but a unary prefix operator that convertsits operand to a number, in the same manner as Number()

...

Why is the first {} interpreted as a code block? Because the completeinput is parsed as a statement and curly braces at the beginning of astatement are interpreted as starting a code block. Hence, you can fixthings by forcing the input to be parsed as an expression:

({} + {})

'[object Object][object Object]'

关于javascript - 为什么括号中的加号运算符的工作方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31584200/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com