2013-03-25 116 views
1

在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使迭代器无效?我该如何解决这个问题?

回答

7

你可以在JavaScript 1.6或更高版本的Array对象上使用过滤方法。

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结账上面链接的兼容性部分的。

+0

谢谢。正确的语法是'$ scope.categories = $ scope.categories.filter(countFilter);' – Ben 2013-04-11 12:37:43

+0

是否有任何不支持javascript版本1.6的主流浏览器? – Ben 2013-04-11 12:45:56

+0

只有IE 8及更早的版本。 http://kangax.github.io/es5-compat-table/(我修正了我的类型谢谢!) – rgaskill 2013-04-12 01:15:15

2

我只是创建一个具有非零计数的新数组。事情是这样的:

// 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; 

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

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