微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 更好的方法在数组中查找对象而不是循环?

链接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
})

问题

在上面的例子中,我有一个包含对象的数组.我需要找到名称为”John Doo’的对象

我的.each循环正在工作,但这部分将执行100次,测试将包含更多的对象.所以我认为这种方式会很慢.

indexOf()将无法工作,因为我无法在对象中搜索名称.

如何在当前数组中搜索name =’John Doo’的对象?

解决方法

jQuery $.grep(或其他过滤函数)不是最佳解决方案.

$.grep函数将循环遍历数组的所有元素,即使在循环期间已找到搜索的对象.

从jQuery grep文档:

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.

如果你的数组没有排序,没有什么可以打败这个:

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

}

原文地址:https://www.jb51.cc/js/155211.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐