从数组中移除元素会使迭代器失效



在AngularJS中,我试图从类别数组中删除所有计数为0的类别。

// remove all categories that have a count of 0
i = 0;
angular.forEach( $scope.categories, function( category )
{           
    if( category.count == 0)
    {
        $scope.categories.splice( i, 1 );
    }
    i++;
});

这段代码从数组中删除第一个计数为0的类别,但不删除下一个类别。我想,splice使迭代器无效?我该如何解决这个问题?

可以在javascript 1.6或更高版本的Array对象中使用filter方法。

function countFilter(category, index, array) {
  return (category.count != 0);
}
$scope.categories = $scope.categories.filter(countFilter);
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter

如果您需要支持旧版本的javascript,请查看上面链接的兼容性部分

我将创建一个非零计数的新数组。像这样:

// remove all categories that have a count of 0
var nonZeroCategories = [];
angular.forEach( $scope.categories, function( category )
{           
    if( category.count > 0)
    {
        nonZeroCategories.push(category)
    }
});
$scope.categories = nonZeroCategories;

另外,作为一个参考,迭代器函数有第二个参数,它是索引,所以如果你需要它,你不需要在forEach之外声明i。你可以这样做:

angular.forEach( $scope.categories, function( category, i ) {
    .....

最新更新