Javascript 对数组中的对象属性求和
我必须得到单价的总和。我该怎么做 该数组如下所示:Javascript 对数组中的对象属性求和,javascript,angularjs,arrays,Javascript,Angularjs,Arrays,我必须得到单价的总和。我该怎么做 该数组如下所示: $scope.items = [ { id: '1', name: 'Phone', quantity: '1', unit_price: '200' }, { id: '2', name: 'IPhone', quantity: '1', unit_price: '240' } ];
$scope.items = [
{
id: '1',
name: 'Phone',
quantity: '1',
unit_price: '200'
},
{
id: '2',
name: 'IPhone',
quantity: '1',
unit_price: '240'
}
];
您可以
减少
阵列:
var total = $scope.items.reduce(function(x,y) { return x + parseInt(y.unit_price) }, 0);
您可以
减少
阵列:
var total = $scope.items.reduce(function(x,y) { return x + parseInt(y.unit_price) }, 0);
试试这个:
var sum = 0;
angular.forEach($scope.items, function(value, key){
sum = sum + value.unit_price;
});
试试这个:
var sum = 0;
angular.forEach($scope.items, function(value, key){
sum = sum + value.unit_price;
});
尽管您可以使用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',
姓名:'电话',
数量:“1”,
单价:'200'
},
{
id:'2',
名称:“IPhone”,
数量:“1”,
单价:'240'
}
];
设和=0;
对于($scope.items的const{unit_price}){
总和+=+单价;
}
控制台日志(总和)代码>尽管可以使用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',
姓名:'电话',
数量:“1”,
单价:'200'
},
{
id:'2',
名称:“IPhone”,
数量:“1”,
单价:'240'
}
];
设和=0;
对于($scope.items的const{unit_price}){
总和+=+单价;
}
控制台日志(总和)代码>请发布a和一些努力请发布a和一些努力这是解决方案:)这是解决方案:)