从数组中获取特定对象而不需要循环的最佳方法

best way to get a specific object from and array without looping

本文关键字:循环 不需要 最佳 方法 对象 数组 获取      更新时间:2023-09-26

在我的angular应用程序的一个控制器中,我设置了一个变量,如下所示:

SomeService.get({}, function(data){
    // this sets xyz as the list of the data retrieved 
    // from the resource within the controllers scope
    $scope.xyz = data.objects;    
});

现在$scope.xyz看起来像

[
    0: {id: 1, ...more data here ...},
    1: {id: 2, ...more data here ...},
    2: {id: 3, ...more data here ...},
    3: {id: 4, ...more data here ...},
    4: {id: 5, ...more data here ...},
    5: {id: 6, ...more data here ...},
]

我要做的是使用id属性(不是列表索引)在xyz中获得一个对象。我知道我可以像下面这样遍历数组。

angular.forEach($scope.xyz, function(obj){ return obj.id == 1;});

但是有没有一种方法可以让我不遍历列表呢?

虽然这个问题在一年前就已经有人回答过了,但由于这是谷歌搜索结果中排名靠前的结果之一,我想我可以添加以下建议,这可能是最简单的过滤方法。在你的控制器中注入$filter之后,

var result = $filter('filter')($scope.xyz, {id:"1"});

参考:https://docs.angularjs.org/api/ng/filter/filter

不,除非满足一些先决条件,否则您无法真正避免循环(O(n))。

  • 如果数组按id排序,可以使用二进制搜索算法(O(log n))。
  • 如果数组索引总是对应id-1(或一些类似的简单公式),可以直接在O(1)中访问。

如果最初没有满足这些条件,但需要通过id多次访问项,那么将它们以这种形式(排序/构建散列映射)引入可能会有所帮助。