我想在javascript数组中执行搜索,该数组显示与查询相关的所有结果,类似于以下SQL语句:
"SELECT * FROM table WHERE column LIKE input"
以下是一个例子:
var array = [];
array[0] = "Apple";
array[1] = "Apricot";
array[2] = "Pear";
array[3] = "Peacock";
假设我的查询字符串为“ap”,它将按以下顺序返回结果:
1. "Apple"
2. "Apricot"
query = "p"
result:
1. "Pear"
2. "Peacock"
3. "Apple"
4. "Apricot"
query = "r"
result:
1. "Apricot"
2. "Pear"
这可以在javascript中使用吗?怎么样?
答案 0 :(得分:1)
试试这个,
var arr = [];
arr[0] = "Apple";
arr[1] = "Apricot";
arr[2] = "Pear";
arr[3] = "Peacock";
var resultArr=[];
var str='ap'//string to search
for(var i=0;i<arr.length;i++){
if(arr[i].indexOf(str) != -1){
resultArr.push(arr[i]);
}
}
alert('search results:'+resultArr);
//resultArr contains reults
答案 1 :(得分:1)
var array = [];
array[0] = "Apple";
array[1] = "Apricot";
array[2] = "Pear";
array[3] = "Peacock";
function searchArray(query){
resultArray = [];
for(var i=0;i<query.length-1;i++){
var char = query.charAt(i);
if(array[i].indexOf(char)!=null){
resultArray.push(array[i]);
}
}
return resultArray;
}
这是未经测试的,就在我的头顶。但是你应该在resultArray中找到你想要的结果