这听起来像是一份工作Array.prototype.filter
。
您还没有描述数据结构,所以我假设一个Object数组。
假设你有这个数据结构,
var all_items = [
{url: 'a', title:'First Entry', description:'Foo'},
{url: 'b', title:'Second Entry', description:'Bar'},
{url: 'c', title:'Third Entry', description:'FooBar'}
// etc..
];
你可以写一个基于.filter
这样的搜索功能
function search(arr, str, url /* =true */, title /* =true */, desc /* =false */) {
var src_fnc;
// set true defaults
if (undefined === url) url = true;
if (undefined === title) title = true;
// toBool
url = url && true || false;
title = title && true || false;
desc = desc && true || false;
// make function
src_fnc = function (e) {
if (url && e.url.indexOf(str) >= 0) return true;
if (title && e.title.indexOf(str) >= 0) return true;
if (desc && e.description.indexOf(str) >= 0) return true;
return false;
};
return arr.filter(src_fnc);
}
然后调用它
search(all_items, 'ir');
/* [
{url: 'a', title:'First Entry', description:'Foo'},
{url: 'c', title:'Third Entry', description:'FooBar'}
] */