让我们考虑一下终端中的以下输入
✗ node
Welcome to Node.js v13.1.0.
Type ".help" for more information.
> let a = 13
undefined
> {} + a.toString()
13
> // but
undefined
> let b = {} + a.toString()
undefined
> b
'[object Object]13'
问题是为什么当您评估{} + a.toString()
时REPL会显示数字13,但是将其分配给变量时它等于预期的字符串'[object Object]13'
?
此行为至少在V8(节点和Chrome)中发生。
答案 0 :(得分:1)
这里的根本问题是JS中的{
... }
在语法上是 block语句或对象文字表达式,取决于上下文(期望是声明还是表达式)。在第二种情况下,它显然是一个表达式:
let b = /*expression context*/
因此{}
是那里的对象文字。在第一种情况下,它在声明上下文中,因此被解释为:
{} // an empty block statement
+ a.toString() // a unary plus operator on "13"