在數(shù)組中求和屬性值的更好方法我有這樣的事情:$scope.traveler = [
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 },];現(xiàn)在,為了獲得這個數(shù)組的總數(shù),我執(zhí)行如下操作:$scope.totalAmount = function(){
var total = 0;
for (var i = 0; i < $scope.traveler.length; i++) {
total = total + $scope.traveler[i].Amount;
}
return total;}當(dāng)只是一個數(shù)組時很容易,但是我有其他的數(shù)組,它們具有不同的屬性名,我想要與它們相加。如果我能做這樣的事,我會更高興的:$scope.traveler.Sum({ Amount });但我不知道如何通過這樣一種方式來重復(fù)使用它:$scope.someArray.Sum({ someProperty });回答我決定用@grff-兔子的建議,所以我避免原型本機(jī)對象(陣列)我剛剛對他的答案做了一些修改,驗證了數(shù)組,和的值不為空,這是我的最后實現(xiàn):$scope.sum = function (items, prop) {
if (items == null) {
return 0;
}
return items.reduce(function (a, b) {
return b[prop] == null ? a : a + b[prop];
}, 0);};
在數(shù)組中求和屬性值的更好方法
函數(shù)式編程
2019-07-15 16:45:17