有没有比使用jQuery数组更好的搜索JavaScript数组的方法?

问题描述:

我经常需要搜索一个包含对象的javascript数组.我想在具有属性匹配的数组中搜索一个对象.例如,在一个Person对象数组中搜索该人的id/key ==="ABC123"

I often have the need to search a javascript array that contains objects. I want to search for an object in the array that has a property match. For example, searching an array of Person objects for where the person's id/key === "ABC123"

使用$ .each方法可以很容易地使用jQuery完成此操作,这正是我所确定的.您可以在jsFiddle中看到示例. http://jsfiddle.net/johnpapa/EJAFG/

It can be done pretty easily using jQuery using the $.each method, which is what I settled on. You can see the example here in jsFiddle. http://jsfiddle.net/johnpapa/EJAFG/

我想知道是否还有其他人找到了更快,更好的方法?

I'm wondering if anyone else has found a faster and/or better way to do this?

var Person = function(code, name) {
    this.code = code;
    this.name = name;
};
var people = [
    new Person("ABC123", "Tooth Fairy"),
    new Person("DEF456", "Santa Claus"),
    new Person("PIR000", "Jack Sparrow"),
    new Person("XYZ987", "Easter Bunny")
    ];

var utils = {};
// Could create a utility function to do this
utils.inArray = function(searchFor, property) {
    var retVal = -1;
    $.each(this, function(index, item) {
        if (item.hasOwnProperty(property)) {
            if (item[property].toLowerCase() === searchFor.toLowerCase()) {
                retVal = index;
                return false;
            }
        }
    });
    return retVal;
};

// or we could create a function on the Array prototype indirectly
Array.prototype.inArray = utils.inArray;

// let's use the prototype for now
var i = people.inArray("PIR000", "code");
$('#output').text(people[i].name);

有很多与此问题类似的问题,但是我还没有看到一个除了迭代之外还有其他解决方案的问题(就像我在这里所做的那样).

There are lot's of questions similar to this one, but I have yet to see one with a solution other than iterating (like I did here).

所以问题是...还有更好的方法吗?

So the question is ... is there a better way?

$.我想每个都将是O(n).找到适用项目时中断的任何简单"for"循环最多为O(n),但平均会更少,除非不断发现数组的后一项是匹配元素. Array.filter是一种有效的方法,但不适用于某些浏览器.如果您希望使用Array.filter方法,则可以使用纯JavaScript实现.对于本机托管的浏览器,由于其实现可能是用本机代码编译和运行的,因此它的执行速度可能会更快.但是filter方法在将数组元素过滤"到新数组中时始终会产生O(n).

$.each would be about O(n) I would think. Any simple "for" loop that breaks when it finds an applicable item would be at most O(n) but would on average be less unless the latter items of the array were constantly found to be the matching elements. Array.filter is a method that works but is not native to some browsers. There are pure javascript implementations of the Array.filter method if you so wished to use it. For the browsers that host it natively, it would probably execute faster as their implementation is probably compiled and ran in native code. But the filter method would always yield O(n) as it "filters" the elements of the array into a new array.

我个人会坚持使用for(int i = 0; ...)方法.可以通过调用其他函数来减少范围更改的开销,并且您可以轻松地中断"匹配的元素.

I'd personally stick with the for(int i=0;...) approach. Less overhead of scope changing by calling other functions and you can easily "break" on a matched element.

我还想补充一点,您可以使用HTML 5提供的本地数据库存储(它使用SqlLite).显然,它不受广泛支持,但在数据量足够大的情况下,它比任何其他JavaScript方法都快得多.如果您想检出链接,请点击以下链接:

I also wanted to add that you could use local database storage(which uses SqlLite) provided by HTML 5. This is obviously not widely supported but would be MUCH faster than any other javascript approach given a large enough set of data. Here is a link if you want to check it out:

http://blog.darkcrimson.com/2010/05/local-databases/

以下是一种行之有效的方法:从理论上讲,您可以索引数据并使用这些索引快速检索数据.无需将数据存储在javascript数组中,而是将其存储在DOM中,然后使用CSS类(例如"data-id-5")索引"元素.这为您提供了使用大多数主要浏览器内置的本机选择器API的优势.这是一个示例:

Here is a somewhat off the wall way of doing it: You could theoretically index your data and retrieve it using those indicies in a fast manner. Instead of storing your data in a javascript array, you store it in the DOM and "index" the elements using CSS classes like "data-id-5". This gives you the advantage of using the native selector API built-in to most major browsers. Here is an example:

DOM:

 <div id="datastuff" style="display:none">
     <span class="data-id-ABC123" data-person='{"code": "ABC123", "name": "Tooth Fairy"}'></span>
     <span class="data-id-DEF456" data-person='{"code": "DEF456", "name": "Santa Claus"}'></span>
     <span class="data-id-PIR000" data-person='{"code": "PIR000", "name": "Jack Sparrow"}'></span>
     <span class="data-id-XYZ987" data-person='{"code": "XYZ987", "name": "Easter Bunny"}'></span>
 </div>

现在我们可以使用jQuery并对其进行查询: 我们将查询"ABC123"的密钥:

Now we can use jQuery and query for it: We'll query for key of "ABC123":

var person = $(".data-id-ABC123").data("person");
console.log(person.name);//Tooth Fairy