gpt4 book ai didi

javascript - 如何使数组相加?

转载 作者:行者123 更新时间:2023-12-03 01:32:32 26 4
gpt4 key购买 nike

我想添加一个数组相加。

假设有一个数组 [7, 1, 21, 70]

在数组索引为 0 的情况下,它只是 7。在数组索引为 1 的情况下,我希望它是 7 + 1 (8)。数组索引 2, 7 + 1 + 21 (29)。数组索引 3 7 + 1 + 21 + 70 (99)。

这是我当前的代码:

var pot = {
'id': 1,
'name': ['stalin', 'hitler', 'mao', 'kim jong-il'],
'amount': [50, 10, 150, 500],
'percentages': new Array()
}

var random = Math.random()*100;
var random = String(random).split(".")[0];
console.log(random);

function potTotal(amounts) {
var sum = 0;
for (var key in amounts) {
sum += pot['amount'][key];
}
return sum;
}

function potPercentage(total, amounts) {
for (var key in amounts) {
var percentage = amounts[key] / total * 100;
var percentage = String(percentage).split(".")[0];
var percentage = Number(percentage);
pot['percentages'].push(percentage);
}
}

potPercentage(potTotal(pot['amount']), pot['amount']);

function ranging(total, percentages) {
console.log(percentages);
for(var i = 0; percentages < i; i++) {
console.log(percentages[i]);
}
}
//[7, 1, 21, 70]
ranging(random, pot['percentages']);

for (var key in pot['percentages']) {
console.log(key);
console.log(pot['percentages'][key]);
}

返回结果:

69
[ 7, 1, 21, 70 ]
0
7
1
1
2
21
3
70

最佳答案

reduce 是为执行此类任务而定义的函数。

const arr = [7, 1, 21, 70].reduce((acc, el, i) => [...acc, (acc[i-1] || 0) + el], []);
console.log(arr);

关于javascript - 如何使数组相加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51223401/

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