gpt4 book ai didi

javascript - 如何将先前索引值的总和存储在一个数组中?

转载 作者:行者123 更新时间:2023-11-28 04:28:36 26 4
gpt4 key购买 nike

这里我更新了我的示例代码,

var distanceSumOfprev = 0;
var distancesArr = [1000, 2000, 1000, 2000, 1000, 2000];
for (var i = 1; i < distancesArr.length; i++) {
distanceSumOfprev += distancesArr[i]
console.log(distanceSumOfprev);
}

这是我目前得到的

  distanceSumOfprev = [2000, 3000, 5000, 6000, 8000];

预期结果

distanceSumOfprev = [2000, 4000, 6000, 7000, 9000];

最佳答案

var distancesArr = [1000, 2000, 1000, 2000, 1000, 2000];
// since we need to add each value with value at previous index, distanceSumOfprev is initialized with value corresponding to first index.
var distanceSumOfprev = distancesArr[0];
for (var i = 0; i < distancesArr.length - 1; i++) {
//distanceSumOfprev will be having the sum of all values upto the index pointing to current loop variable.
distanceSumOfprev += distancesArr[i + 1];
console.log(distanceSumOfprev);
}

请检查一下

关于javascript - 如何将先前索引值的总和存储在一个数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45256574/

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