Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

javascript - Why does Node REPL not give the same results as Wat video or my browser console?

For example, in both Wat and in my Chrome browser:

{} + {}

is NaN

But in Node REPL, it's

[object Object][object Object]

The latter admittedly makes more sense to me - coercing to string and then acting is a pretty reasonable thing to do. However I don't understand where this discrepancy comes from, and therefore, don't understand how much I can trust the REPL to understand some simple JS behavior.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

{} is both an expression (an empty object literal) and a statement (an empty block).

eval() will try to parse its input as a statement.
If it isn't a "normal" statement (eg, an if), it will be parsed as an expression statement, which evaluates an expression.

Therefore, {} + {} is parsed as two statements (via ASI): {}; +{}. The first statement is an empty block; the second statement is the unary + operator which coerces an object to a number.
Coercing an object to a number involves calling toString() (which returns "[object Object]"), then parsing the result as a number (which it isn't).
eval() then returns that as the value of the final statement.

Node wraps its REPL input in () to force it to be parsed as an expression:

  // First we attempt to eval as expression with parens.
  // This catches '{a : 1}' properly.
  self.eval('(' + evalCmd + ')',

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...