Typeahead.js substringMatcher函数的解释
Explanation of Typeahead.js substringMatcher function
我正在对 Typeahead.js
做一些研究,它是一个非常酷的库。由于文档也非常好,我已经设法获得了一个基本示例。
但是我想弄清楚下面的代码块实际上在做什么?
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// 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);
};
};
在示例中,它是在将预输入初始化为 source
选项时传入的。我可以理解它是从文本框中获取输入并将其与数据集进行比较,但我对 q
和 cb
是什么感到有点困惑?
q
是要搜索的值。这被传递到正则表达式匹配器中,并且搜索不区分大小写("i" 参数)
cb
是 returns 从搜索中找到匹配项的回调函数。
findMatches
基本上是一个匿名函数,用作 substringMatcher
函数的实现。
我正在对 Typeahead.js
做一些研究,它是一个非常酷的库。由于文档也非常好,我已经设法获得了一个基本示例。
但是我想弄清楚下面的代码块实际上在做什么?
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// 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);
};
};
在示例中,它是在将预输入初始化为 source
选项时传入的。我可以理解它是从文本框中获取输入并将其与数据集进行比较,但我对 q
和 cb
是什么感到有点困惑?
q
是要搜索的值。这被传递到正则表达式匹配器中,并且搜索不区分大小写("i" 参数)
cb
是 returns 从搜索中找到匹配项的回调函数。
findMatches
基本上是一个匿名函数,用作 substringMatcher
函数的实现。