{} + []-为什么是0或[object Object]? [英] {} + [] - why it is 0 or [object Object]?

查看:64
本文介绍了{} + []-为什么是0或[object Object]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在浏览器中打开JS控制台(在我的情况下为Chrome),然后键入:

If you open a JS Console in your browser (in my case Chrome) and type:

{} + []

您将获得0,但是当您键入

you will get 0, but when you type

console.log({} + [])

您得到[object Object] ...任何想法为何结果不同?我一直以为,当您在其中键入内容时,总是用console.log包裹它吗?

you get [object Object]... any ideas why the result is different? I've always thought that when you type there it always wrap it with console.log?

推荐答案

{} 可以是空的 block 或空的 object文字>视情况而定.

{} can either be an empty block or a empty object literal depending on context.

+ 可以是一元加号运算符,也可以是隐含运算符,具体取决于上下文.

+ can either be the unary plus operator or the concatination operator depending on context.

第一个代码示例是一个空块,它也可能不存在,使表达式与 + [] 相同,表示将空数组转换为数字".

The first code example is an empty block it might as well not be there, making the expression the same as +[], meaning "An empty array converted to a number".

您不能使用块作为函数参数,因此第二个代码示例 {} 是一个对象,并且代码的意思是用数组组合一个对象"(隐式转换对象和对象).数组转换为字符串).

You can't have a block as a function argument, so the second code example {} is an object and the code means "Concatinate an object with an array" (implicitly converting both object and array to strings).

这篇关于{} + []-为什么是0或[object Object]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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