如何使用forEach制作部分和的列表 [英] How to make a list of partial sums using forEach

查看:61
本文介绍了如何使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆