在数组中求和属性值的更好方法我有这样的事情:$scope.traveler = [
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 },];现在,为了获得这个数组的总数,我执行如下操作:$scope.totalAmount = function(){
var total = 0;
for (var i = 0; i < $scope.traveler.length; i++) {
total = total + $scope.traveler[i].Amount;
}
return total;}当只是一个数组时很容易,但是我有其他的数组,它们具有不同的属性名,我想要与它们相加。如果我能做这样的事,我会更高兴的:$scope.traveler.Sum({ Amount });但我不知道如何通过这样一种方式来重复使用它:$scope.someArray.Sum({ someProperty });回答我决定用@grff-兔子的建议,所以我避免原型本机对象(阵列)我刚刚对他的答案做了一些修改,验证了数组,和的值不为空,这是我的最后实现:$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);};
3 回答
qq_笑_17
TA贡献1818条经验 获得超7个赞
再来一次,这就是 native
JavaScript函数 Map
和 Reduce
是为(Map和Remote是多种语言的引擎)而构建的。
var traveler = [{description: 'Senior', Amount: 50}, {description: 'Senior', Amount: 50}, {description: 'Adult', Amount: 75}, {description: 'Child', Amount: 35}, {description: 'Infant', Amount: 25}];function amount(item){ return item.Amount;}function sum(prev, next){ return prev + next;}traveler.map(amount).reduce(sum);// => 235; // or use arrow functionstraveler.map(item => item.Amount).reduce((prev, next) => prev + next);
注
通过单独设置更小的函数,我们可以再次使用它们。
// Example of reuse.// Get only Amounts greater than 0;// Also, while using Javascript, stick with camelCase. // If you do decide to go against the standards, // then maintain your decision with all keys as in... // { description: 'Senior', Amount: 50 }// would be// { Description: 'Senior', Amount: 50 };var travelers = [{description: 'Senior', amount: 50}, {description: 'Senior', amount: 50}, {description: 'Adult', amount: 75}, {description: 'Child', amount: 35}, {description: 'Infant', amount: 0 }]; // Directly above Travelers array I changed "Amount" to "amount" to match standards.function amount(item){ return item.amount;}travelers.filter(amount);// => [{description: 'Senior', amount: 50}, // {description: 'Senior', amount: 50},// {description: 'Adult', amount: 75}, // {description: 'Child', amount: 35}];// Does not include "Infant" as 0 is falsey.
添加回答
举报
0/150
提交
取消