为什么{} + []在Javascript中返回0? [英] Why does {} + [] return 0 in Javascript?
问题描述
我知道当 []
被强制转换为字符串时它会返回空字符串(),当
{}
被强制转换为字符串时,它返回[object Object]
。
I know that when []
is coerced to a string it returns the empty string (""
), and when {}
is coerced to a string it returns "[object Object]"
.
当我运行 [] + {}
在我的浏览器的Javascript控制台中,它会按照我的预期返回:
When I run [] + {}
in my browser's Javascript console, it returns as I would expect:
>> [] + {}
"[object Object]"
但是当我运行 {} + []
,它会返回一个完全意外的值:
But when I run {} + []
, it returns a completely unexpected value:
>> {} + []
0
什么可能导致它返回 0
?
推荐答案
当有 {
在语句的开头,它将被解释为一个块,它可能包含零个或多个语句。其中没有语句的块将具有空的延续值。
When there is a {
at the beginning of a statement, it will be interpreted as a block, which may contain zero or more statements. An block with no statements in it will have an empty continuation value.
换句话说,在这种情况下, {}
被解释为空代码块。
In other words, in this case, {}
is interpreted as an empty code block.
语句在结束括号}
之后结束,这意味着接下来的三个字符 + []
包含他们自己的声明。
The statement ends after the ending brace }
, which means that the next three characters +[]
comprise a statement of their own.
在表达式或语句的开头, +
是一元加号运算符,它将其操作数强制转换为数字。
At the beginning of an expression or statement, +
is the unary plus operator, which coerces its operand to a number.
所以 + []
与 Number([])
相同,其计算结果为 0
。
So +[]
is the same as Number([])
, which evaluates to 0
.
简而言之, {} + []
是一个空代码块,后跟一个数组强迫一个号码。
In short, {} + []
is an empty code block followed by an array coerced to a number.
所有这些都说,如果你评价 {} + []
在表达式中,它会返回您的预期:
All that said, if you evaluate {} + []
inside an expression, it will return what you expect:
>> ({} + [])
"[object Object]"
另一件有趣的事情是你不能用对象文字开始一个语句,因为解释器会尝试将它解析为一个语句。这样做
Another interesting thing is that you cannot begin a statement with an object literal because the interpreter will try to parse it as a statement. Doing this
{ "object": "literal" };
会抛出语法错误。
这篇关于为什么{} + []在Javascript中返回0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!