我有一个对象数组,每个对象都有一个唯一的 ID
我想获取数组中每个对象的索引。我正在使用 Angular,但出于本次练习的目的,我无法使用 $index。
$scope.getObjectIndex = function(obj) {
var theArray = _.flatten($scope.myObjects);
var index;
//CAN I SEARCH THE ARRAY FOR MY OBJ USING IT'S ID?
return index;
}
如有任何意见或建议,我们将不胜感激。
最佳答案
如果您对数组使用 ng-repeat,您就可以访问索引。
<div ng-repeat="item in myCtrl.obj">
<span>{{myCtrl.getObjectIndex(index)}}</span>
</div>
在你的 Controller 中你可以搜索你的obj并获取你的id:
$scope.getObjectIndex=function(index){
return $scope.myObjects[index].id;
}
但是如果我们想使用您的解决方案,您可以使用 for 循环搜索您的数组,如下所示:
$scope.getObjectIndex=function(obj){
for(var $i=0;$i<$scope.myObjects.length;$i++){
if(obj.id===$scope.myObjects[$i].id){
return $i;
}
}
}
关于javascript - 返回数组中每个对象的 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26100154/