gpt4 book ai didi

javascript - 我可以让这个功能更简洁吗

转载 作者:行者123 更新时间:2023-11-30 07:00:15 24 4
gpt4 key购买 nike

我有这个 javascript 片段,我想知道我是否可以在 reduce 函数的单次传递中计算出 amountusers

root.children.forEach(function(v) {

v.amount = v.children.reduce(function(a, b) {
console.log(a);
return {
amount: a.amount + b.amount
}
}, {
'amount': 0
}).amount

v.users = v.children.reduce(function(a, b) {
console.log(a);
return {
users: a.users + b.users
}
}, {
'users': 0
}).users

})

最佳答案

是的,你可以像下面那样做,

root.children.forEach(function(v) {
var obj = v.children.reduce(function(a, b) {
a.amount += b.amount;
a.users += a.users;
}, {'amount': 0, 'users' : 0 });
v.amount = obj.amount;
v.users = obj.users;
});

关于javascript - 我可以让这个功能更简洁吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40529046/

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