0

我想在 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中可能吗?如何?

4

2 回答 2

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 中得到你正在寻找的结果

于 2013-10-24T15:42:39.737 回答
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 
于 2013-10-24T15:38:51.550 回答