为什么在{{} + 1`在Chrome和Firefox中获得数字1,而在Node.js中使用'[object Object] 1'? [英] Why does `{} + 1` get number 1 in Chrome and Firefox, but string '[object Object]1' in Node.js?

查看:150
本文介绍了为什么在{{} + 1`在Chrome和Firefox中获得数字1,而在Node.js中使用'[object Object] 1'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

但在Node.js中, {} + 1 等于字符串'[object Object] 1'。另一方面,在浏览器和Node.js中, 1 + {} 等于'1 [object Object]'

谁能解释为什么 {} + 1 在浏览器中等于1吗?

解决方案

复杂。发生这种情况是因为大多数JavaScript引擎将 {} 解释为代码块,而不是对象。因此 {} + 1 基本上与 +1 相同。 (例如)

 ({} + 1})

括号()中的代码将被解释为一个表达式,而不是代码块。因此 {} 变成了一个实际的对象。



阅读这个更多细节:

http://www.2ality.com/ 2012/01 / object-plus-object.html



这篇文章也解释了为什么Node.Js不同。


Addition in Javascript is really amazing.
In Chrome and Firefox, {} + 1 equals number 1; but in Node.js, {} + 1 equals string '[object Object]1'. On other hand, 1 + {} equals '1[object Object]' in both browsers and Node.js.
Who can explain why {} + 1 equals 1 in the browsers?

解决方案

This a bit complicated. This happens, because most JavaScript engines interpret {} as a code block, not object. Thus {}+1 is essentially the same as +1. If you do (for example)

({}+1})

then the code inside brackets () will be interpreted as a expression, not code block. Thus {} becomes an actual object.

Read this for more details:

http://www.2ality.com/2012/01/object-plus-object.html

The article also explains why it is different in Node.Js.

这篇关于为什么在{{} + 1`在Chrome和Firefox中获得数字1,而在Node.js中使用'[object Object] 1'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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