我试图将数组中的每个数字与下一个数字相加并保存所有结果: 这是我的例子:
var arr = [2, 3, -6, 2, -1, 6, 4];
我必须对 2 + 3 求和并保存它,然后 2 + 3 - 6 保存它,接下来 2 + 3 - 6 - 1 保存它等等......到数组的末尾。接下来与第二个索引 3 - 6 相同并保存它,3 - 6 + 2... 我知道这可以通过两个嵌套循环来完成,但不知 Prop 体该怎么做。 我哪里错了?
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);
最佳答案
下面使用一个函数reduce将一个数组转换成其渐进和的数组。
您可以重复调用该函数,同时从数组中删除项目以对整个结果进行求和。
这是一个简洁的版本:
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));
为了清楚起见,这里有一个扩展版本。
逻辑:
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
代码:
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);
关于javascript - 如何迭代数组中的每个数字并将它们与同一数组中的其他数字相加 - JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52634803/