我对使用下划线/Node 一窍不通,并且正在尝试理解链接函数的概念。但是,在尝试链接 Node 中的函数时,我无法引出正确的输出。从下划线的链接部分抓取示例片段会产生“无效的 REPL 关键字”:
var __ = require("underscore"); //for underscore use in node
var lyrics = [
{line: 1, words: "I'm a lumberjack and I'm okay"},
{line: 2, words: "I sleep all night and I work all day"},
{line: 3, words: "He's a lumberjack and he's okay"},
{line: 4, words: "He sleeps all night and he works all day"}
];
__.chain(lyrics) //in the console chain appears to run and return correctly, but then
.map(function(line) { return line.words.split(' '); }) //Invalid REPL keyword
.flatten() //Invalid REPL keyword
.reduce(function(counts, word) {
counts[word] = (counts[word] || 0) + 1;
return counts;
}, {}) //Invalid REPL keyword
.value(); //Invalid REPL keyword
我是ASI的受害者吗?在这种情况下?如果是这样,';' 在哪里试图被插入?我很困惑,因为将此代码段插入 JSHint 不会产生任何错误。你们中的一位能帮我找出错误吗?
谢谢!
最佳答案
我猜你在某种程度上遇到了 ASI,因为通常插入分号来分隔表达式。不过,从更一般的意义上讲,您正在做的是输入 Node 的 REPL。 (在不带参数的情况下运行 node
时得到的结果),在 REPL 环境中,如果一行可以单独执行,它会打印出结果。
这与标准的 JS 环境不同,标准的 JS 环境会在执行之前完全处理整个函数/文件。
您遇到的错误,Invalid REPL keyword
, 是因为 Node 的 REPL 有一组全部以 .
开头的命令,例如 .clear
( the full list is here ), 和 .map
这些是 JS 函数,而不是 REPL 命令。
例如,如果我以你的例子重新排序 .
s 到行尾(这样每一行都不能单独处理),它将在 REPL 中工作:
var __ = require("underscore"); //for underscore use in node
var lyrics = [
{line: 1, words: "I'm a lumberjack and I'm okay"},
{line: 2, words: "I sleep all night and I work all day"},
{line: 3, words: "He's a lumberjack and he's okay"},
{line: 4, words: "He sleeps all night and he works all day"}
];
__.chain(lyrics).
map(function(line) {
return line.words.split(' ');
}).
flatten().
reduce(function(counts, word) {
counts[word] = (counts[word] || 0) + 1;
return counts;
}, {}).
value();
不过,实际上,您应该使用 REPL 的唯一时间是进行快速测试,其中单行行为通常很有帮助。在进行正常开发时,您应该在文件中工作并运行 node <filename>
测试您的代码。
关于javascript - 在 node.js 中链接 underscore.js 抛出 'Invalid REPL keyword',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21739612/