Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 对数组中的对象属性求和_Javascript_Angularjs_Arrays - Fatal编程技术网

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和一些努力这是解决方案:)这是解决方案:)