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

}

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...