如何在一个数组中存储以前索引值的总和?

时间:2017-07-22 16:06:10

标签: javascript jquery html css

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

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];

6 个答案:

答案 0 :(得分:4)

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);
}

请检查

答案 1 :(得分:3)

您可以使用最后一笔的闭包并映射数组的其余部分。

var array = [1000, 2000, 1000, 2000, 1000, 2000],
    result = array.map(function (s) {
        return function(a) {
            return s += a;
        };
    }(array.shift()));

console.log(result);

ES6

var array = [1000, 2000, 1000, 2000, 1000, 2000],
    result = array.map((s => a => s += a)(array.shift()));

console.log(result);

答案 2 :(得分:0)

您正在寻找的是被称为cumsum,它是累积总和的缩写 以下代码演示了如何在原始数组的副本上执行此操作:

&#13;
&#13;
var distancesArr = [1000, 2000, 1000, 2000, 1000, 2000];
var cumSumArr = distancesArr.slice();
for (var i = 1; i < distancesArr.length; i++) {
    cumSumArr[i] += cumSumArr[i-1];
}
console.log(distancesArr);
console.log(cumSumArr);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我认为你的意思是输出数组应该以{{1​​}}开头。然后,我们所要做的就是在现有循环内再添加一个For i = 2 To 20 If Not Rows(i).Hidden 'do stuff End If End With 循环向后3000

&#13;
&#13;
for
&#13;
&#13;
&#13;

由于这里的小调整,您可以获得所需的输出: [3000 *,4000,6000,7000,9000]

答案 4 :(得分:0)

您可以使用reduce()并返回新数组。

var distancesArr = [1000, 2000, 1000, 2000, 1000, 2000];

var result = distancesArr.reduce((function(c) {
  return (r, e, i) => (i == 0 ? c = e : r.push(c += e), r)
})(0), [])

console.log(result)

答案 5 :(得分:0)

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