1

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

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>
4

4 回答 4

6

循环中的简单循环

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

于 2012-10-05T14:28:24.510 回答
4

我认为在这个问题中实现目标的更优雅的方法是使用jQuery.grep()——参见http://api.jquery.com/jquery.grep/

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"}
];

var matchingItems = $.grep(devices, function(e) {
            return (e["Manufacturer"].indexOf(search_input) > -1 ||
                    e["Model"].indexOf(search_input) > -1);
});

现在matchingItems包含一组在制造商或模型属性中具有 search_input 字词的项目,您可以在 html 中输出这些项目。

于 2014-12-21T20:41:18.657 回答
1

我认为你需要:

jQuery.inArray()

http://api.jquery.com/jQuery.inArray/

于 2012-10-05T14:17:37.603 回答
1

另一种方法是用映射(JavaScript 对象)替换您的数组,其中键是您要与 search_input 进行比较的值。这样,您只需查找密钥并获取对象。

var devices = {"Amazon Kindle": {"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"}}

第二步涉及将 JavaScript 对象转换为 XML,此处已在 SO 上回答了将 JavaScript 对象序列化为 XML 的最佳方法是什么?

于 2012-10-05T14:23:12.360 回答