javascript/jquery 简单搜索引擎 - 实现一个简单的搜索引擎,数据存储在一个数组中

javascript/jquery simple search engine - implement a simple search engine, data stored in an array

问题已编辑! 我已将所有产品名称存储在 数组 对象格式.我也有一个输入[type=text]。我需要一个简单的代码来搜索这个数组。 SQL 命令类似于:(SELECT name FROM tbl_product WHERE name LIKE %txt% )。但是我是在前端实现的,没有连接到后端!

<input type="text" id="mytxt" />

<script>
// [{ in_ordered_id : "product name"}, ...]
var products_name = [{ 8 : "product ninety two"}, {21 : "product two"}, {35 : "product nine"} , ....];
$("#mytxt").keyup(function(){
     var txt = $("#mytxt").val();
     var results = start_search(txt); // `results` must be array of ids e.g. [35, 98]

});

function start_search(text){
     /// I don't know what to write here
}
</script>

string.includes 可能有帮助

products_name = ["product one", "product two"];


$("#mytxt").keyup(function() {
  var txt = $("#mytxt").val();
  var results = start_search(txt);
  console.log(results);
});

function start_search(text) {
  return products_name.filter(pr => pr.includes(text))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="mytxt">

--编辑

const products_name = [{
  8: "product ninety two"
}, {
  21: "product two"
}, {
  35: "product nine"
}]


$("#mytxt").keyup(function() {
  var txt = $("#mytxt").val();
  var results = start_search(txt);
  console.log(results);
});

function start_search(text) {
  return products_name.filter(pr => Object.values(pr)[0].includes(text)).map(pr => Number(Object.keys(pr)[0]))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="mytxt">

使用array.indexOf功能怎么样?

products_name = ["product one", "product two"];

function start_search(text){
     if(products_name.indexOf(text) > -1){
        return true;
    }else{
        return false;
    }
};

start_search('product'); // returns false
start_search('product one'); // returns true
start_search('product two'); // returns true
start_search('product three'); // returns false