为什么Node REPL根据是否将其分配给变量来对表达式进行不同的计算?

时间:2019-11-08 18:07:05

标签: javascript node.js

让我们考虑一下终端中的以下输入

✗ 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)中发生。

1 个答案:

答案 0 :(得分:1)

这里的根本问题是JS中的{ ... }在语法上是 block语句对象文字表达式,取决于上下文(期望是声明还是表达式)。在第二种情况下,它显然是一个表达式:

 let b = /*expression context*/

因此{}是那里的对象文字。在第一种情况下,它在声明上下文中,因此被解释为:

  {} // an empty block statement
  + a.toString() // a unary plus operator on "13"