[] + is equal to [object Object], in Javascript? How? [duplicate]
Posted
技术标签:
【中文标题】[] + is equal to [object Object], in Javascript? How? [duplicate]【英文标题】:[] + is equal to [object Object], in Javascript? How? [duplicate][] + is equal to [object Object], in Javascript? How? [duplicate] 【发布时间】:2012-05-14 18:32:12 【问题描述】:可能重复:What is the explanation for these bizarre javascript behaviours mentioned in the 'Wat' talk for CodeMash 2012?
我对 JavaScript 很陌生。我有这样的代码:
<script type="text/javascript">
console.log( [] + );
</script>
在我的 Google chrome 浏览器上记录:
[object Object]
我觉得它是有线的!并做这样的事情:
<script type="text/javascript">
console.log( + );
</script>
确实产生:
[object Object][object Object]
这两种情况下到底发生了什么?为什么[]
, 将这两个结果添加到
objects
的数组中?
提前致谢。
【问题讨论】:
shopify.com/technology/… 这个问题被问了好多次了!!! 爆炸,回答时没有意识到这是重复的。啊,嗯…… 抱歉,我尝试搜索[] +
,但没有得到任何相关答案!
@Ant's:是的,很难搜索...
【参考方案1】:
当您将+
operator 与非数字一起使用时,您正在执行字符串连接,因此操作数将转换为字符串。一个空数组becomes an empty string,因为它是对join
的隐式调用,并且没有条目,join
返回一个空字符串;一个对象becomes "[object Object]"
。
所以
console.log( [] + );
...归结为
console.log( String([]) + String() );
...归结为
console.log( "" + "[object Object]");
【讨论】:
【参考方案2】:您正在将对象添加到数组 - 所以它被放在最后。当您对 2 个对象应用 + 时,唯一有意义的操作是转换为字符串并连接它
【讨论】:
【参考方案3】:[]
是一个空数组,它被转换为字符串(由于连接运算符)。 是一个空对象。
【讨论】:
以上是关于[] + is equal to [object Object], in Javascript? How? [duplicate]的主要内容,如果未能解决你的问题,请参考以下文章
matplotlib (equal unit length): with 'equal' aspect ratio z-axis is not equal to x- and y-
chainmaker VerifyingBlock height is not equal to proposed block
ORA-01476: divisor is equal to zero解决方法
工作记录之ORacleSQL报错:oracle ORA-01476:divisor is equal to zero
kafkaThe replication factor in manual replication assignment is not equal to the existing replica(代码
ElasticsearchResult window is too large, from + size must be less than or equal to: [10000]