如何使用 forEach 列出部分总和 [英] How to make a list of partial sums using forEach
本文介绍了如何使用 forEach 列出部分总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,看起来像这样:
I have an array of arrays which looks like this:
changes = [ [1, 1, 1, -1], [1, -1, -1], [1, 1] ];
我想通过添加最后一个值来获取数组中的下一个值
I want to get the next value in the array by adding the last value
values = [ [1, 2, 3, 2], [1, 0, -1], [1, 2] ];
到目前为止,我已经尝试使用 forEach:
so far I have tried to use a forEach:
changes.forEach(change => {
let i = changes.indexOf(change);
let newValue = change[i] + change[i + 1]
});
我认为我在正确的路线上,但我无法让这种方法发挥作用,或者可能有更好的方法来做到这一点.
I think I am on the right lines but I cannot get this approach to work, or maybe there is a better way to do it.
推荐答案
您可以保存总和并添加值.
You could save a sum and add the values.
var array = [[1, 1, 1, -1], [1, -1, -1], [1, 1]],
result = array.map(a => a.map((s => v => s += v)(0)));
console.log(result);
通过使用forEach
,您需要取对象引用和前一个值或零.
By using forEach
, you need to take the object reference and the previous value or zero.
var array = [[1, 1, 1, -1], [1, -1, -1], [1, 1]];
array.forEach(a => a.forEach((v, i, a) => a[i] = (a[i - 1] || 0) + v));
console.log(array);
这篇关于如何使用 forEach 列出部分总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文