这听起来像是Array.prototype.filter
的工作。
您尚未描述数据结构,因此我将假设阵列的对象 s。
说你有这样的数据结构,
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'}
] */
嗯...我正在考虑为每个页面设置一个单独的数组对象,并让引擎检查每个字符串是否匹配(因为peo ple会在大多数时间搜索特定的单词)。然后,如果发现匹配,它将返回:“匹配发现在这些页面中: - 模块1-食物; - 模块5 - 旅行。” 谢谢,顺便说一句。 – 2013-04-08 16:32:27
为此,只需使用适当的数组而不是'all_items'(以及其他修复以使函数与您的数据匹配)运行此函数'x'次,其中'x'是您拥有_Array_的数量。 – 2013-04-08 16:36:29
好的。谢谢。你有其他建议吗?这是一种不好的做法吗?还有其他更有效的方法吗?你更好吗?我真的在努力学习,我知道我不应该做半分的编码... – 2013-04-08 16:44:03