Kid*_*man 3 javascript node.js underscore.js hoisting
我是使用下划线/节点的n00b,我试图理解链接函数的概念.但是,在尝试链接节点中的函数时,我无法获得正确的输出.从下划线的链接部分抓取示例snipp会生成"Invalid REPL keyword":
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
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我是ASI的受害者吗?如果是这样的话,';' 试图插入?我很困惑,因为将此片段插入JSHint不会产生任何错误.你们其中一个人可以帮我识别错误吗?
谢谢!
我猜你在某种程度上遇到了ASI,因为通常会将分号插入到单独的表达式中.但是在更一般的意义上,你正在做的是键入Node的REPL(当你node没有args 运行时得到的东西),在REPL环境中,如果一行可以自己执行,它将会及其结果打印出来.
这与标准JS环境不同,后者将在执行之前完全处理整个函数/文件.
你得到的错误Invalid REPL keyword,是因为Node的REPL有一组所有开头的命令.,例如.clear(完整列表在这里),等等.map是JS函数,而不是REPL命令.
因此,例如,如果我将您的示例重新排序.到行的末尾(以便每行不能自行处理),它将在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();
Run Code Online (Sandbox Code Playgroud)
实际上,您应该使用REPL的唯一时间是快速测试,其中单行行为通常很有帮助.在进行正常开发时,您应该在一个文件中运行并运行node <filename>以测试您的代码.
| 归档时间: |
|
| 查看次数: |
3770 次 |
| 最近记录: |