我想做的事情:
使用多个搜索字符串搜索多维数组。
我目前正在做的事情示例:
var multiArray = [['Apples and pears', 'tuna salad'],['bananas tuna'],['the colour blue']];
var singleArray = [];
var match_array = [];
// Turn multiple arrays into one big one
for (var i = 0; i < multiArray.length; i++) {
for (var x = 0; x < multiArray[i].length; x++) {
singleArray.push(multiArray[i][x]);
}
}
// Create a new array from matched strings
function find_match(to_match) {
for (var i in singleArray) {
if (singleArray[i].indexOf(to_match)!= -1)
match_array.push(singleArray[i]);
}
return (match_array.length === 0 ? null : match_array);
}
// Find matching terms for match_array
find_match('tuna');
find_match('the');
alert(match_array);
JSFiddle演示
问题:
显然,这是一种杂乱无章的方式。这怎么可能流线型(即直接搜索
multiArray
,而不使用多个find_match
功能(?如何只获得精确的字符串匹配,最好不分解多维数组?
你对搜索海量内容有什么想法多维数组?
你想要这样的东西吗?
var multiArray = [['Foo', 'Bar'],['Foo'],['Bar']];
var singleArray = [];
var match_array = [];
// Turn multiple arrays into one big one
for (var i = 0; i < multiArray.length; i++) {
for (var x = 0; x < multiArray[i].length; x++) {
singleArray.push(multiArray[i][x]);
}
}
// Create a new array from matched strings
function find_match(to_match, where_search) {
for (var j in where_search) {
if(where_search[j] instanceof Array){
find_match(to_match, where_search[j]);
}else{
for (var i in to_match) {
if (where_search[j].indexOf(to_match[i]) ==0 &&
where_search[j].length == to_match[i].length)
match_array.push(where_search[j]);
}
}
}
return (where_search.length === 0 ? null : match_array);
}
// Find matching terms for match_array
find_match(['Foo', 'Bar'],multiArray);
alert(match_array);