创建累积和在JavaScript数组 [英] Creating an array of cumulative sum in javascript

查看:112
本文介绍了创建累积和在JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是什么,我需要做的一个例子:

This is an example of what I need to do:

var myarray = [5, 10, 3, 2];

var result1 = myarray[0];
var result2 = myarray[1] + myarray[0];
var result3 = myarray[2] + myarray[1] + myarray[0];
var result4 = myarray[3] + myarray[2] + myarray[1] + myarray[0];

让所有将输出5,15,18,20

so all that would output 5, 15, 18, 20

但不是写出像所有的增值经销商,我希望它这样说:

but instead of writing out all the vars like that, I want it to say something like:

var result = arrayitem + the sum of any previous items 

这是否有意义?那可能吗?我怎么做?

Does that make sense? Is that possible? How do I do that?

推荐答案

JavaScript的减少提供当前指数,这是在这里有用:

Javascript's reduce provides the current index, which is useful here:

var myarray = [5, 10, 3, 2];
var new_array = [];
myarray.reduce(function(a,b,i) { return new_array[i] = a+b; },0);
new_array // [5, 15, 18, 20]

这篇关于创建累积和在JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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