{} - 0 VS ({} - 0) 在 JavaScript 中 [英] {} - 0 VS ({} - 0) in JavaScript
问题描述
在 Chrome JavaScript 控制台中,为什么将语句 {} - 0
括在括号中会改变返回值?
In the Chrome JavaScript console, why does wrapping the statement {} - 0
in parentheses change the returned value?
{} - 0 // Returns -0
({} - 0) // Returns NaN
将单个语句括在括号中会改变包含的值,这似乎非常奇怪.我在这里错过了什么?
It seems incredibly strange that wrapping a single statement in parentheses alters the contained value. What am I missing here?
推荐答案
{} - 0
行有两种可能的解释:
There are two possible interpretations of the line {} - 0
:
- 可以理解为
{};-0
,其中{}
被解释为空块语句,-
是一元否定运算符(所以-0
只是负零").求值时 this 的值是最后一条语句的值,即 -0. - 可以解释为
({} - 0)
,其中{}
被解释为空对象,-
是减法运算符(因此从{}
中减去0
).
- It can be interpreted as
{}; -0
, where{}
is interpreted as an empty block statement, and-
is the unary negation operator (so-0
is just "negative zero"). The value of this when evaluated is the value of the last statement, which is -0. - It can be interpreted as
({} - 0)
, where{}
is interpreted as an empty object, and-
is the subtraction operator (so0
is subtracted from{}
).
在您的第一行中,这是模棱两可的,因此它将选择第一种解释.在第二行中,第一个解释是无效的(因为块语句永远不能成为表达式的一部分,你用括号强制它).
In your first line, this is ambiguous, so it will choose the first interpretation. In the second line, the first interpretation is invalid (as a block statement can never be part of an expression, which you're forcing with the parantheses).
这篇关于{} - 0 VS ({} - 0) 在 JavaScript 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!