gpt4 book ai didi

javascript - 在数组或类似的对象上使用 jQuery.find()

转载 作者:行者123 更新时间:2023-11-30 07:02:45 24 4
gpt4 key购买 nike

假设我有一个搜索框,其中输入的任何内容都存储为:

var search_input = $(this).val();

我如何用这个值搜索我的数组?

var devices = [{"Device_ID":"43","Image":"Amazon-Kindle-Fire.png","Manufacturer":"Amazon","Model":"Kindle Fire","Type":"Tablet"},{"Device_ID":"44","Image":"Apple-iPad.png","Manufacturer":"Apple","Model":"iPad","Type":"Tablet"}]

假设我的 search_input 变量中有 Amazon 或 Kindle 等,我希望它搜索数组并输出以下内容。这同样适用于任何键入的内容或数组中的任何内容

<div id="device">43</div>
<div id="image">Amazon-Kindle-Fire.png</div>
<div id="name">Amazon Kindle Fire</div>

最佳答案

循环中的简单循环

var devices = [{"Device_ID":"43","Image":"Amazon-Kindle-Fire.png","Manufacturer":"Amazon","Model":"Kindle Fire","Type":"Tablet"},{"Device_ID":"44","Image":"Apple-iPad.png","Manufacturer":"Apple","Model":"iPad","Type":"Tablet"}];

function findItem (term) {
var items = [];
for (var i=0;i<devices.length;i++) {
var item = devices[i];
for (var prop in item) {
var detail = item[prop].toString().toLowerCase();
if (detail.indexOf(term)>-1) {
items.push(item);
break;
}
}
}
return items;
}

console.log( findItem("amazon") ); //returns one item
console.log( findItem("kindle") ); //returns one item
console.log( findItem("apple") ); //returns one item
console.log( findItem("tablet") ); //returns two items
console.log( findItem("nerd") ); //returns zero items

jsFiddle

关于javascript - 在数组或类似的对象上使用 jQuery.find(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12748203/

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