更好的方式来找到阵列,而不是循环对象呢? [英] Better way to find object in array instead of looping?

查看:91
本文介绍了更好的方式来找到阵列,而不是循环对象呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

链接: http://jsfiddle.net/ewBGt/

var test = [{
    "name": "John Doo"
}, {
    "name": "Foo Bar"
}]

var find = 'John Doo'

console.log(test.indexOf(find)) // output: -1
console.log(test[find]) // output: undefined

$.each(test, function(index, object) {
    if(test[index].name === find)
        console.log(test[index]) // problem: this way is slow
})

问题

在上面的例子中我有对象的数组。我需要找到具有对象 NAME =约翰斗

我的。每个循环工作,但是这部分将被执行100次,测试将包含更多的对象。所以我觉得这种方式将是缓慢的。

My .each loop is working, but this part will be executed 100 times and test will contain lot more objects. So I think this way will be slow.

的indexOf()将无法工作,因为我不能搜索对象的名称。

The indexOf() won't work because I cannot search for the name in object.

我怎么能在我目前的阵列搜索对象与 NAME =约翰斗

How can I search for the object with name = 'John Doo' in my current array?

推荐答案

jQuery的 $。gr​​ep的(或其他过滤功能)不是最佳的解决方案。

jQuery $.grep (or other filtering function) is not the optimal solution.

通过的 $。gr​​ep的函数将循环全部的数组中的元素,即使搜索到的对象的循环期间已经找到

The $.grep function will loop through all the elements of the array, even if the searched object has been already found during the loop.

从jQuery的grep的文档:

From jQuery grep documentation :

这是一个数组的项目作为必要的,这样的$ .grep()方法删除
  所有剩余项目通过提供的测试。测试是一个函数,它
  传递一个数组项目,该项目的数组中的索引。
  只有当测试返回true,将会把该项目的结果数组中

The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

只要你的数组没有排序,没有什么可以打败这样的:

Provided that your array is not sorted, nothing can beat this:

var getObjectByName = function(name, array) {

    // (!) Cache the array length in a variable
    for (var i = 0, len = test.length; i < len; i++) {

        if (test[i].name === name)
            return test[i]; // Return as soon as the object is found

    }

    return null; // The searched object was not found

}

这篇关于更好的方式来找到阵列,而不是循环对象呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆