gpt4 book ai didi

javascript - 添加对象数组中包含的值

转载 作者:行者123 更新时间:2023-12-01 02:27:48 25 4
gpt4 key购买 nike

我将如何添加对象内的所有值?

例如 amoutpay": ["4222","1000"] 会给我 5222

这是我的对象:

{
"amoutpay": [ "4222", "1000" ],
"amtpending": [ "778", "4000" ],
"totalcost": [ "5000", "5000" ],
"coursename": [ "Office Automation", "ajaba" ]
}

我想要的是将值添加到变量中。我会使用拆分吗?

var a =
var b =
var c =

最佳答案

您可以使用Array.prototype.reduce()如下图:

var obj = {
"amoutpay": [ "4222", "1000" ],
"amtpending": [ "778", "4000" ],
"totalcost": [ "5000", "5000" ],
"coursename": [ "Office Automation", "ajaba" ]
},

a = obj.amoutpay.reduce(function(prevVal, curVal, curInd) {
return +prevVal + +curVal;
}),
b = obj.amtpending.reduce(function(prevVal, curVal, curInd) {
return +prevVal + +curVal;
}),
c = obj.totalcost.reduce(function(prevVal, curVal, curInd) {
return +prevVal + +curVal;
});

console.log( a, b, c );

或者您可以更进一步,定义自己的数组方法,例如 Array.prototype.sum():

var obj = {
"amoutpay": [ "4222", "1000" ],
"amtpending": [ "778", "4000" ],
"totalcost": [ "5000", "5000" ],
"coursename": [ "Office Automation", "ajaba" ]
};

Array.prototype.sum = function() {
return this.reduce(function( prv, cur, ind ) {
return +prv + +cur;
});
};

var a = obj.amoutpay.sum(),
b = obj.amtpending.sum(),
c = obj.totalcost.sum();

console.log( a, b, c );

关于javascript - 添加对象数组中包含的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38634413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com