如何迭代数组中的每个数字并将它们与同一数组中的其他数字相加 - JS

Sim*_*mba 2 javascript arrays loops nested

我正在尝试将数组中的每个数字与下一个数字相加并保存所有结果:这是我的示例:

var arr = [2, 3, -6, 2, -1, 6, 4];
Run Code Online (Sandbox Code Playgroud)

我必须加2 + 3并保存,然后2 + 3 - 6保存,接下来2 + 3 - 6 - 1保存它等等到数组的末尾.接下来相同的第二个索引3 - 6并保存,3 - 6 + 2 ...我知道这可以通过两个嵌套循环完成,但不知道如何做到这一点.哪里我错了?

const sequence = [2, 3, -6, 2, -1, 2, -1, 6, 4]
const sums = [];

for (let i = 0; i < sequence.length; i++) {

  for (let z = 1; z < sequence.length; z++) {
    let previous = sequence[z - 1] + sequence[z];
    sums.push(previous + sequence[z + 1])
  }
}

console.log(sums);
Run Code Online (Sandbox Code Playgroud)

Tyl*_*per 5

以下使用函数将数组减少为其渐变总和的数组.

您可以重复调用该函数,同时从数组中删除项目以对整个事物求和.

这是一个简洁的版本:

var arr = [2, 3, -6, 2, -1, 6, 4];

var listSums = (array) => array.reduce((a,b) => [...a, a[a.length-1]+b], [0]).slice(2);
var listAllSums = (array) => array.reduce((a, b, index) => [...a, ...listSums(array.slice(index))], []);

console.log(listAllSums(arr));
Run Code Online (Sandbox Code Playgroud)

为了清晰起见,这是一个扩展版本.

逻辑:

Add the sums of [2, 3, -6, 2, -1, 6, 4] to the list
Add the sums of [   3, -6, 2, -1, 6, 4] to the list
Add the sums of [      -6, 2, -1, 6, 4] to the list
...
Add the sums of [             -1, 6, 4] to the list
Add the sums of [                 6, 4] to the list

Output the list
Run Code Online (Sandbox Code Playgroud)

代码:

var arr = [2, 3, -6, 2, -1, 6, 4];

function sumArray(array) {
    var result = array.reduce(function(accumulator,currentInt) {
      var lastSum = accumulator[accumulator.length-1];   //Get current sum
      var newSum = lastSum + currentInt;                 //Add next integer
      var resultingArray = [...accumulator, newSum];     //Combine them into an array
      return resultingArray;                             //Return the new array of sums
    }, [0]);                                             //Initialize accumulator
    return result.slice(2);
}

var result = arr.reduce(function(accumulator, currentInt, index) {  //For each item in our original array
    var toSum = arr.slice(index);               //Remove x number of items from the beginning (starting with 0)
    var sums = sumArray(toSum);                 //Sum the array using the function above
    var combined = [...accumulator, ...sums];   //Store the results
    return combined;                            //Return the results to the next iteration
  }, []);                                       //Initialize accumulator

console.log(result);
Run Code Online (Sandbox Code Playgroud)