书中的例子(不是整本书,如果需要,我会提供更多).
function CSVReader(separators) {
this.separators = separators || [","];
this.regexp =
new RegExp(this.separators.map(function(sep) {
return "\\" + sep[0];
}).join("|"));
}
Run Code Online (Sandbox Code Playgroud)
功能中的sep参数是什么?
当我看不到它在任何地方声明时,我如何得到它的价值?
...当我看不到它在任何地方宣布?
它在回调参数列表中声明...
function CSVReader(separators){
this.separators = separators || [","];
this.regexp =
new RegExp(this.separators.map(function(sep){
// -----------------------------------------^^^^ ---------------------- here
return "\\"+sep[0];
}).join("|"));
}
Run Code Online (Sandbox Code Playgroud)
该map函数将为this.separators数组中的每个条目调用该回调.在每次调用中,sep参数都会接收该条目的值.
遗漏了很多细节,map基本上是这样的:
function map(callback) {
// Here, `this` is the array `map` was called on
var result = [];
for (var i = 0, len = this.length; i < len; ++i) {
result.push(callback(this[i], i, this));
}
}
Run Code Online (Sandbox Code Playgroud)
(为清楚起见,我遗漏的主要细节之一是forEach's thisArg并且callback使用特定this值进行调用.)
回调接收三个参数,但示例中的一个只使用其中一个参数sep.
另见这个答案约forEach.
FWIW:MDN是JavaScript信息(以及HTML和CSS)的良好资源.