3

我是使用下划线/节点的 n00b 并且正在尝试理解链接函数的概念。但是,当尝试在节点中链接函数时,我无法得出正确的输出。从下划线的链接部分获取示例片段会产生“无效的 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 不会产生错误。你们中的一个可以帮我找出错误吗?

谢谢!

4

1 回答 1

8

我猜你在某种程度上遇到了 ASI,因为通常分号被插入到单独的表达式中。不过,从更一般的意义上说,您正在做的是输入 Node 的REPL(在node没有 args 的情况下运行时得到的结果),并且在 REPL 环境中,如果一行可以自己执行,它将执行,其结果将被打印出来。

这与标准 JS 环境不同,标准 JS 环境将在执行之前完全处理整个函数/文件。

您得到的错误Invalid REPL keyword是因为 Node 的 REPL 有一组以 开头的命令.,例如.clear完整列表在这里),.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>以测试您的代码。

于 2014-02-12T22:28:32.657 回答