gpt4 book ai didi

javascript - 立即将函数返回给函数有什么好处?

转载 作者:行者123 更新时间:2023-11-30 12:22:04 25 4
gpt4 key购买 nike

我指的是它将函数 findMatches 返回到 substringMatcher 的位置。substringMatcher 现在接受一个或两个参数吗?

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);
};
};

最佳答案

这是一个闭包。为了解释,我强烈建议通过 this .我自己无法更好地解释它。我只会从那里引用:

Simply accessing variables outside of your immediate lexical scope creates a closure.

要调用您的函数,您可以编写 substringMatcher(strs)(q, cb); 所以答案是 substringMatcher 接受一个参数并返回一个接受两个参数的函数。你也可以这样写:

var findMatches = substringMatcher(strs);
var result = findMatches(q, cb);

关于javascript - 立即将函数返回给函数有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30662684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com