在 Node.js 中使用 Underscore 模块

我一直在学习 node.js 和模块,但似乎无法让 Underscore 库正常工作... ... 似乎我第一次使用 Underscore 中的函数时,它用函数调用的结果覆盖了 _ object。有人知道怎么回事吗?例如,这里有一个来自 node.js REPL 的会话:

Admin-MacBook-Pro:test admin$ node
> require("./underscore-min")
{ [Function]
_: [Circular],
VERSION: '1.1.4',
forEach: [Function],
each: [Function],
map: [Function],
inject: [Function],
(...more functions...)
templateSettings: { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g },
template: [Function] }
> _.max([1,2,3])
3
> _.max([4,5,6])
TypeError: Object 3 has no method 'max'
at [object Context]:1:3
at Interface.<anonymous> (repl.js:171:22)
at Interface.emit (events.js:64:17)
at Interface._onLine (readline.js:153:10)
at Interface._line (readline.js:408:8)
at Interface._ttyWrite (readline.js:585:14)
at ReadStream.<anonymous> (readline.js:73:12)
at ReadStream.emit (events.js:81:20)
at ReadStream._emitKey (tty_posix.js:307:10)
at ReadStream.onData (tty_posix.js:70:12)
> _
3

当我自己创建 Javascript 文件并导入它们时,它们似乎正常工作。也许下划线图书馆有什么特别的东西?

109749 次浏览

Node REPL 使用下划线变量来保存最后一次操作的结果,因此它与 Underscore 库使用同一个变量相冲突。试试这样:

Admin-MacBook-Pro:test admin$ node
> _und = require("./underscore-min")
{ [Function]
_: [Circular],
VERSION: '1.1.4',
forEach: [Function],
each: [Function],
map: [Function],
inject: [Function],
(...more functions...)
templateSettings: { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g },
template: [Function] }
> _und.max([1,2,3])
3
> _und.max([4,5,6])
6

或者:

    var _ = require('underscore')._;

node.js REPL 用来保存前一个输入的名称 _。请选择另一个名称。

从今天起,您可以像往常一样在 Node.js 代码中使用下划线。前面的评论是正确的,指出 REPL 接口(Node 的命令行模式)使用“ _”来保存最后的结果,但是你可以在你的代码文件上使用它,它将工作没有问题,通过做标准:

var _ = require('underscore');

注意: 下面的代码只适用于下一行代码,并且只是由于巧合。

和 Lodash 一起,

require('lodash');
_.isArray([]); // true

没有 var _ = require('lodash'),因为 Lodash 在需要时神秘地将此值设置为全局值。