简体   繁体   English

为什么`{} + []`在Javascript中从`a = {} + []`返回不同的结果?

[英]Why does `{} + []` return a different result from `a = {} + []` in Javascript?

In (at least) Firefox Web Console and JSBin, I get 在(至少)Firefox Web Console和JSBin中,我得到了

> {} + []
0
> a = {} + []
"[object Object]"

Node.js returns "[object Object]" in both cases. 在两种情况下,Node.js都返回"[object Object]" Which behavior is correct according to the spec? 根据规范,哪种行为是正确的? If the first, why? 如果是第一个,为什么?

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 + [] . 由于块是空的,它什么都不做,留下+ []

The unary plus operator converts the array to a number, which is 0 . 一元加运算符将数组转换为数字,即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. 当对象使用运算符时,javascript解释器应使用valueOf方法将值转换为基元,该方法实际上使用内部ToPrimitive函数将类型转换中继到对象的内部[[DefaultValue]]方法。

Your example with the plus operator is a bit tricky because the operator can acts both as math addition or string concatenation. 使用plus运算符的示例有点棘手,因为运算符既可以作为数学加法也可以作为字符串连接。 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(). 由于数组为空,因此toString方法返回一个空字符串,这就是为什么正确的结果应该是[object Object],它是object.valueOf()toString()的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM