Ron*_*den 6 javascript arrays jquery object
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 = 'John Doo'
我的.each循环正在工作,但这部分将执行100次,测试将包含更多的对象.所以我认为这种方式会很慢.
这indexOf()将无法工作,因为我无法在对象中搜索名称.
如何name = 'John Doo'在当前数组中搜索对象?
在这种情况下,我有时会做"可搜索的地图对象".如果数组本身是静态的,则可以转换为映射,其中数组值可以是键和映射值索引.我假设值在您的示例中是唯一的.
Lo-Dash (www.lodash.com)创建了utils选项,可以轻松循环等.查看它!
注意:但通常你真的不必担心使用100个元素循环使用数组.
jQuery $.grep(或其他过滤功能)不是最佳解决方案.
该$.grep函数将循环遍历数组的所有元素,即使在循环期间已找到搜索的对象.
从jQuery grep文档:
$ .grep()方法根据需要从数组中删除项目,以便所有剩余项目都通过提供的测试.测试是一个传递数组项的函数和数组中项的索引.仅当测试返回true时,该项才会位于结果数组中.
如果你的数组没有排序,没有什么可以打败这个:
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
}
| 归档时间: | 
 | 
| 查看次数: | 18025 次 | 
| 最近记录: |