{} + []和[] + {}结果如何不同 [英] How can {} + [] and [] + {} results be different

查看:52
本文介绍了{} + []和[] + {}结果如何不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
这些奇怪的JavaScript的解释是什么在CodeMash 2012的"Wat"演讲中提到的行为?

有人可以向我解释,您返回的结果在javascript中可能会有所不同:

Could someone explain to me how thees returning results can be different in javascript:

› {} + []
» 0
› [] + {}
» "[object Object]"

推荐答案

这是因为代码中的 {} 不是对象常量,而是一个空块

This is because the {} in the code is not an object literal, but an empty block.

它被解析为:

{};   // empty block
+ []; // this result is shown in the console

({})+ [] 进行比较,其结果与 [] + {} 相同;在这种情况下,圆括号迫使 {} 被在表达式上下文中"处理/解析.

Compare with ({}) + [] which yields the same results as [] + {}; in this case the parenthesis force the {} to be treated/parsed "in an expression context".

SO上有关于这些 {} 的特殊双重性质的副本( bunch )(作为表达式或块?),但是,找到它们可能有些棘手...

There are a bunch of duplicates on SO about this particular dual-nature of {} (as an expression or block?) but, finding them can be somewhat tricky ..

我发现 https在Meta上://://meta.stackexchange.com/questions/83911/how-do-i-search-stackoverflow-for-at-keywords-like-private-or-synthesize 上,并使用Symbolhound作为最近的"我可以在问题

I found https://meta.stackexchange.com/questions/83911/how-do-i-search-stackoverflow-for-at-keywords-like-private-or-synthesize on Meta, and using Symbolhound the "closest" duplicates I could find resolved around questions like this (that relate to the need to add parenthesis when "eval'ing JSON") or this (where the use of constructs like "{} == false" is a syntax error).

如果有人知道搜索此类问题的更好方法,或者链接到此类重复方便的话..

If anyone knows a better way to search SO for this sort question, or has a link to such a duplicate handy ..

这篇关于{} + []和[] + {}结果如何不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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