2013-03-25 60 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) { 
    .....