Angularjs 从数组中删除元素会使迭代器无效

Angularjs 从数组中删除元素会使迭代器无效,angularjs,Angularjs,在AngularJS中,我试图从categories数组中删除计数为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 ); }

在AngularJS中,我试图从categories数组中删除计数为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的第一个类别,但不删除下一个类别。我想,拼接使迭代器无效?如何解决此问题?

我只需要创建一个计数非零的新数组。大概是这样的:

// 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 ) {
    .....

我只需要创建一个非零计数的新数组。大概是这样的:

// 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 ) {
    .....

您可以使用javascript版本1.6或更高版本的数组对象上可用的筛选方法

function countFilter(category, index, array) {
  return (category.count != 0);
}
$scope.categories = $scope.categories.filter(countFilter);

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

您可以使用javascript 1.6版或更高版本的数组对象上可用的筛选方法

function countFilter(category, index, array) {
  return (category.count != 0);
}
$scope.categories = $scope.categories.filter(countFilter);

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

谢谢。正确的语法是$scope.categories=$scope.categories.filtercountFilter;有没有主流浏览器不支持javascript 1.6版?只有IE 8和更早版本。我改好了我的类型谢谢!谢谢正确的语法是$scope.categories=$scope.categories.filtercountFilter;有没有主流浏览器不支持javascript 1.6版?只有IE 8和更早版本。我改好了我的类型谢谢!