我需要在关联数组的值中搜索字符串,但只搜索字符串示例的开头:
var stack = ['aba', 'abcd', 'ab', 'da', 'da'];
在堆栈上搜索值 a
将返回 ['abc, 'abcd', 'ab']
,对于 b
只会返回 b 而搜索 'd' 会返回 [da', 'da']
...有什么办法吗?
我试图像自动完成选择框那样做,但它是自定义的,所以我需要修改文本事件并搜索我的项目数组以在用户键入时获取第一个匹配项的索引。
最佳答案
upvoted @Mrbuubuu 但你可以把它作为原型(prototype)来做,并通过字符串 .contains
传递过滤器元素,使其更像 mootools 并满足中间的匹配,比如 'cd' which应该返回结果。
例如,一组品牌,其中一个是 the north face
,搜索 north
的用户应该返回匹配的品牌,但不会像他们那样错过了
此外,在比较值时,您需要确保搜索字符串和堆栈数组元素的大小写降低。
这是一个输入有效的例子:http://jsfiddle.net/dimitar/M2Tep/
(function() {
Array.implement({
subStr: function(what) {
return this.filter(function(el) {
return el.charAt(0) == what;
// return el.contains(what); // any position match
});
}
});
})();
// return the original array elements
console.log(['aba', 'abcd', 'ab', 'da', 'da'].subStr("d"));
// ["da", "da"]
或者,您在评论中提到您真正想要获得的只是原始数组中的索引:
(function() {
Array.implement({
getIndexes: function(what) {
var indexes = [];
this.each(function(el, index) {
if (el.charAt(0) == what)
indexes.push(index);
});
return indexes;
}
});
})();
console.log(['aba', 'abcd', 'ab', 'da', 'da'].getIndexes("d"));
// [3,4]
虽然因为这不返回数组,它会破坏链接,因此它不应该是数组的原型(prototype),而只是一个函数。
关于javascript - 搜索数组返回部分匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5440275/