Javascript 将一个函数返回到一个函数会带来什么好处?
我指的是它将函数findMatches返回给substringMatcher的位置。 子字符串匹配器现在接受一个或两个参数吗Javascript 将一个函数返回到一个函数会带来什么好处?,javascript,Javascript,我指的是它将函数findMatches返回给substringMatcher的位置。 子字符串匹配器现在接受一个或两个参数吗 var substringMatcher = function(strs) { return function findMatches(q, cb) { var matches, substringRegex; // an array that will be populated with substring matches matche
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = ["Your Location"];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
这是一个结束。为了便于解释,我强烈建议您仔细阅读。我自己也解释不清楚。我只想引述一下: 只需访问直接词法范围之外的变量 创建一个闭包 为了调用函数,可以编写
子字符串匹配器(strs)(q,cb)所以答案是substringMatcher接受一个参数并返回一个函数,这个函数接受两个参数。你也可以写:
var findMatches = substringMatcher(strs);
var result = findMatches(q, cb);
这是一个高阶函数。它接受一个参数,并返回一个接受两个参数的函数。您可以编写子字符串匹配器(a)(b,c)