2016-06-11 70 views
0

我正在使用下面的代碼循環訪問數組,並向數組中的每個項目添加一個屬性。爲AngularJS地圖函數添加條件

$scope.addresses = $scope.addresses.map(function(address) { 
     address.location = "X"; 
     return address; 
}); 

這個在最後會返回所有的項目。我怎樣才能給循環添加一個條件?所以我可以檢查一個屬性,並基於該屬性返回只有某些地址,該屬性是true

任何幫助表示讚賞!

回答

1

您應該使用filter功能

你可以閱讀一下:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

基本上filter是一個函數獲取一個布爾函數作爲參數(姑且稱之爲f),並返回一個數組與f返回true的所有項目。

例如:

var mapped = $scope.addresses = $scope.addresses.map(function(address) { 
     address.location = "X"; 
     return address; 
}); 

var filtered = mapped.filter(function (address) { 
    return address.location.length > 5; 
}); 

filtered會認爲,有超過500個字符的位置的地址的集合。

+0

能否請您展開 –

+0

當然,將編輯我的回答在一分鐘 –

0

使用過濾器

$scope.addresses = $scope.addresses.filter(function(address){ 
    return address.location === x; 
})