今天我发现了一些关于node.js的奇怪的事情:
$ node
> console.log(_)
ReferenceError: _ is not defined
at repl:1:13
at REPLServer.defaultEval (repl.js:130:27)
at bound (domain.js:257:14)
at REPLServer.runBound [as eval] (domain.js:270:12)
at REPLServer.<anonymous> (repl.js:277:12)
at REPLServer.EventEmitter.emit (events.js:107:17)
at REPLServer.Interface._onLine (readline.js:202:10)
at REPLServer.Interface._line (readline.js:531:8)
at REPLServer.Interface._ttyWrite (readline.js:812:14)
at ReadStream.onkeypress (readline.js:101:10)
> function foo() {}
undefined
> console.log(_)
undefined
undefined
创建函数表达式后会发生同样的事情:
$ node
> console.log(_)
ReferenceError: _ is not defined
at repl:1:13
at REPLServer.defaultEval (repl.js:130:27)
at bound (domain.js:257:14)
at REPLServer.runBound [as eval] (domain.js:270:12)
at REPLServer.<anonymous> (repl.js:277:12)
at REPLServer.EventEmitter.emit (events.js:107:17)
at REPLServer.Interface._onLine (readline.js:202:10)
at REPLServer.Interface._line (readline.js:531:8)
at REPLServer.Interface._ttyWrite (readline.js:812:14)
at ReadStream.onkeypress (readline.js:101:10)
> (function () {}())
undefined
> console.log(_)
undefined
undefined
这非常酷,并且对于您有意将其保留为 未定义
的函数参数来说非常方便,但为什么会发生这种情况呢?我在 Arch Linux 上使用 Node 版本 v0.11.13
。
最佳答案
这是 the repl 的一个功能: _
返回最后一个表达式的结果。
当然,在某些情况下 - 就像您拥有的 console.log - 表达式不会返回结果。但是,是的,这是获取最后一个表达式的值的便捷方法。
当然,这只发生在 REPL 中 - 如果您键入相同的 Node 程序并从文件运行它,_
将在您的控制之下。
关于javascript - Node.js REPL 在函数声明或函数表达式后自动声明下划线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25701665/