gpt4 book ai didi

javascript - 搜索数组,按与查询的相关性显示结果

转载 作者:行者123 更新时间:2023-12-02 18:12:50 27 4
gpt4 key购买 nike

我想在 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 中可能吗?怎么办?

最佳答案

试试这个,

    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

关于javascript - 搜索数组,按与查询的相关性显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19570207/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com