翻转操作数增加时,与空对象空数组会产生不同的结果 [英] Adding empty array with empty object yields different results when flipping operands

查看:72
本文介绍了翻转操作数增加时,与空对象空数组会产生不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好的办法是通过例子来说明:

Best way to describe my question is to illustrate by example :

# node v4.3.1
> {} + []
0
> [] + {}
'[object Object]'
> [] + {} === {} + []
true

我设法找到一个 WAT 谈由加里·哈特说提到了幽默相同的行为途径
但遗憾的是没有解释。

I have managed to find a WAT talk by by Gary Bernhardt that mentions same behaviour in humorist approach but sadly no explanation.

另外平等比较和同一性文档没有帮助在理解的行为。

Also the equality comparisons and sameness docs do not help in understanding the behavior.

同样的行为发现在Firefox,所以我想这应该是这样,但为什么呢?这到底是怎么回事,为什么翻转操作数转换结果?
而更重要的,为什么测试为<一两个前pressions href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Strict_equality_using\"相对=nofollow>全等总是同时我们可以看到,他们的返回值是不同的产生真的吗?

Same behavior spotted in Firefox, so i guess this should be this way, but why ? What is going on here, why flipping the operands changes the result ? and more important why testing both expressions for strict equality always yields true while we see that their return values are different ?

推荐答案

案例 {} + [] :结果
JavaScript的认为 {} 是一个空块语句,它只是忽略。然后 + [] - > +'' - > + 0 - > 0 结果
空块语句转换为对象文字是这样的: {} ,所以固定的版本应该是:({})+ []

Case {} + []:
JavaScript thinks {} is an empty block statement and it's just ignored. Then + [] -> + '' -> + 0 -> 0.
The empty block statement is converted to object literal this way: ({}), so the fixed version should be: ({}) + [].

案例 [] + {} :结果
[] + {} - > ''+'的翻译: - > [对象的对象]

Case [] + {}:
[] + {} -> '' + '[object Object]' -> "[object Object]".

案例 [] + {} === {} + [] :结果
[] + {} === {} + [] - > ''+'的翻译:===[对象的对象]'+'' - > 的翻译:===[对象的对象] - > 真正

Case [] + {} === {} + []:
[] + {} === {} + [] -> '' + '[object Object]' === '[object Object]' + '' -> '[object Object]' === '[object Object]' -> true

注意:


  • 数组是通过转换为原始值的toString()方法,它实际上是一个加入('') [] 转化为原始与 []加入('') - >

  • 常规对象使用转化为原始值的toString()太,在默认情况下返回 [对象的对象]

  • &LT; VALUE&GT; + LT;数值2&GT; 运营商试图改变它的操作数的原始值。然后尝试来连接转换的结果

  • +&LT;价值&GT; 运营商转变操作员原始值,然后将结果转换为数量

  • An array is transformed to a primitive value using toString() method, which is actually an join(','). [] is transformed to a primitive with [].join(',') -> ''
  • The regular Object is transformed to a primitive value using toString() too, which by default returns [object Object]
  • <value> + <value2> operator tries to transform it's operands to primitive values. Then tries to concatenate the result of transformation
  • + <value> operator transforms the operator to primitive value, then the result is converted to a number

了解更多关于此外并的平等运营商。

Read more about addition and equality operators.

这篇关于翻转操作数增加时,与空对象空数组会产生不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆