搜索字符串数组(javascript+angularjs)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18630466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search array for string (javascript+angularjs)
提问by DennisKo
I want to check if an array contains a string and followup on it. indexOf() is not an option because it is strict.
我想检查一个数组是否包含一个字符串并对其进行后续操作。indexOf() 不是一个选项,因为它是严格的。
You can find the described problem in the app.filter('myOtherFilter', function()
您可以在 app.filter('myOtherFilter', function()
app.filter('myOtherFilter', function() {
return function(data, values) {
var vs = [];
angular.forEach(values, function(item){
if(!!item.truth){
vs.push(item.value);
}
});
if(vs.length === 0) return data;
var result = [];
angular.forEach(data, function(item){
if(vs.toString().search(item.name) >= 0) {
result.push(item);
}
});
return result;
}
});
Is this correct and is the error somewhere else?
这是正确的,是其他地方的错误吗?
采纳答案by AlwaysALearner
angular.forEach(data, function(item){
for(var i = 0; i < vs.length; i++){
if(item.name.search(vs[i]) >= 0) {
result.push(item);
}
}
});
回答by Brian Genisio
You could always extract the Angular filter
filter, which takes an array but will handle the different types properly. Here is the general idea:
你总是可以提取 Angularfilter
过滤器,它接受一个数组,但会正确处理不同的类型。这是一般的想法:
app.filter('filter', function($filter) {
var filterFilter = $filter('filter');
function find(item, query) {
return filterFilter([item], query).length > 0;
}
return function(data, values) {
var result = [];
angular.forEach(data, function(item) {
for(var i = 0; i < values.length; i++) {
if(find(item, values[i])) {
result.push(item);
break;
}
}
});
return result;
};
}
});
});
You'll have to change the structure of the data you are passing in. Pass in a list of values, not a list of {truth: true}
. This solution allows you to leverage the existing power of the Angular "filter" filter.
您必须更改传入数据的结构。传入值列表,而不是{truth: true}
. 此解决方案允许您利用 Angular“过滤器”过滤器的现有功能。