如何获得 angular.forEach 的 $index

Jan*_*ski 2 angularjs

我怎样才能获得 angular.forEach() 项目的 $index?

我想要一些这样的:

$scope.data = {
  "name": "foo",
  "info": "bar"
}

angular.forEach($scope.data, function (value, key) {

  console.log($index + ' - ' + value.name + ' - ' + value.info)

})
Run Code Online (Sandbox Code Playgroud)

Aro*_*ron 5

如果您正在遍历数组,则函数中的第二个参数 - 在您的情况下是key- 是索引。

如果像现在这样遍历对象,则无法访问索引。你必须用这样的for in循环来循环它:

var i = 0;
for (var key in $scope.data) {
    if ($scope.data.hasOwnProperty(key)) {
        // Code and stuff
        i++;
    }
}
Run Code Online (Sandbox Code Playgroud)