【问题标题】:Make sum of object properties from array从数组中求和对象属性
【发布时间】:2016-11-10 14:55:56
【问题描述】:
我必须得到 unit_price 数字的总和。我怎样才能做到这一点?
数组如下所示:
$scope.items = [
{
id: '1',
name: 'Phone',
quantity: '1',
unit_price: '200'
},
{
id: '2',
name: 'IPhone',
quantity: '1',
unit_price: '240'
}
];
【问题讨论】:
标签:
javascript
angularjs
arrays
【解决方案1】:
你reduce数组:
var total = $scope.items.reduce(function(x,y) { return x + parseInt(y.unit_price) }, 0);
【解决方案2】:
试试这个:
var sum = 0;
angular.forEach($scope.items, function(value, key){
sum = sum + value.unit_price;
});
【解决方案3】:
虽然您可以为此使用reduce,但没有理由这样做,而且很容易出错。 (reduce 在使用预定义的、可重用的 reducer 进行函数式编程时很有用;否则,它只会过于复杂。)
你只需要一个简单的循环,也许还需要一些解构:
let sum = 0;
for (const {unit_price} of $scope.items) {
sum += +unit_price;
// ^−−−−−−−−−−− converts your strings to numbers
}
现场示例:
const $scope = {};
$scope.items = [
{
id: '1',
name: 'Phone',
quantity: '1',
unit_price: '200'
},
{
id: '2',
name: 'IPhone',
quantity: '1',
unit_price: '240'
}
];
let sum = 0;
for (const {unit_price} of $scope.items) {
sum += +unit_price;
}
console.log(sum);
将您的 unit_price 字符串重新转换为数字:我的回答 here 列出了您执行此操作的各种选项,每个选项都有一些优点和缺点。我使用了上面的一元 +,但还有其他选项。