在javascript中创建一个累积总和数组 [英] Creating an array of cumulative sum in 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?
推荐答案
从 Nina Scholz 复制的优雅解决方案,使用柯里化以访问先前的值.
An elegant solution copied from Nina Scholz, using currying to access the previous value.
const cumulativeSum = (sum => value => sum += value)(0);
console.log([5, 10, 3, 2].map(cumulativeSum));
cumulativeSum
是函数 value =>sum += value
,sum
初始化为零.每次调用时,sum
都会更新,并在下次调用时(输入 [n])等于前一个值 (output[n-1]).
cumulativeSum
is the function value => sum += value
, with sum
initialized to zero. Every time it's called, sum
is updated and will equal the previous value (output[n-1]) when called the next time (with input[n]).
这篇关于在javascript中创建一个累积总和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!