为什么`{} + []`返回的结果不同于Java中的`a = {} + []`? [英] Why does `{} + []` return a different result from `a = {} + []` in Javascript?
本文介绍了为什么`{} + []`返回的结果不同于Java中的`a = {} + []`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在(至少)Firefox Web Console和JSBin中,我得到了
In (at least) Firefox Web Console and JSBin, I get
> {} + []
0
> a = {} + []
"[object Object]"
在两种情况下,
Node.js返回"[object Object]"
.根据规范,哪种行为是正确的?如果是第一个,为什么?
Node.js returns "[object Object]"
in both cases. Which behavior is correct according to the spec? If the first, why?
推荐答案
在浏览器控制台上,当它前面没有 =
(或其他更改其上下文的代码)时, {}
被视为 block ,而不是对象文字.
On the browser console, when it isn't preceded by a =
(or some other code that changes its context), {}
is treated as a block, not an object literal.
由于该块为空,因此不执行任何操作,而保留 + []
.
Since the block is empty it does nothing, leaving + []
.
一元加号运算符将数组转换为数字,即 0
.
The unary plus operator converts the array to a number, which is 0
.
这篇关于为什么`{} + []`返回的结果不同于Java中的`a = {} + []`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文