admin管理员组文章数量:1392101
In (at least) Firefox Web Console and JSBin, I get
> {} + []
0
> a = {} + []
"[object Object]"
Node.js returns "[object Object]"
in both cases. Which behavior is correct according to the spec? If the first, why?
In (at least) Firefox Web Console and JSBin, I get
> {} + []
0
> a = {} + []
"[object Object]"
Node.js returns "[object Object]"
in both cases. Which behavior is correct according to the spec? If the first, why?
- Where is the parison happening? – Alexey Romanov Commented Aug 29, 2013 at 11:59
- 1 Sorry, I was too fast. – bfavaretto Commented Aug 29, 2013 at 12:01
- Wat? destroyallsoftware./talks/wat – Colonel Panic Commented Aug 29, 2013 at 12:05
-
In the spirit of my previous (deleted) ment, and as an aside to Quentin's answer: in the assignment version, both objects are converted to strings when you try to add them, according to ecma-international/ecma-262/5.1/#sec-11.6.1. Thus
"[object Object]"
. – bfavaretto Commented Aug 29, 2013 at 12:09 -
possible duplicate of What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012? or Why is
{a:1, b:2}
a syntax error while{a:1}
is not – Bergi Commented Aug 29, 2013 at 12:17
2 Answers
Reset to default 15On 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 + []
.
The unary plus operator converts the array to a number, which is 0
.
When using an operator against objects the javascript interpreter should cast the values to primitive using the valueOf method which in fact use the internal ToPrimitive function relaying type casting to object's internal [[DefaultValue]] method.
Your example with the plus operator is a bit tricky because the operator can acts both as math addition or string concatenation. In this case it concatenates string representations of the objects.
What is really happening behind the scene is:
a = {}.valueOf().toString() + [].valueOf().toString();
Since the array is empty the toString method returns an empty string, that's why the correct result should be [object Object] which is the return value from object.valueOf()toString().
本文标签: Why doesreturn a different result from a in JavascriptStack Overflow
版权声明:本文标题:Why does `{} + []` return a different result from `a = {} + []` in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744779952a2624647.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论