[英]Running sum of the input array in Javascript
I want to build a function that我想建立一个功能
For example, if I call this function with the input of [1,2,3,4], the output should be [1,3,6,10].例如,如果我以 [1,2,3,4] 的输入调用此函数,则输出应为 [1,3,6,10]。 However, when I run my code, it returns an empty array.
但是,当我运行我的代码时,它返回一个空数组。
The following is the code I got so far.以下是我到目前为止得到的代码。
function sumOfArray(nums) { var output = []; // tip: initialize like let output = [nums?.[0] ?? 0]; for(let i = 1 ; i < nums.length ; i++) { nums[i] = nums[i] + nums[i-1]; output.push(nums[i]); } return output; }; console.log( 'calling sumOfArray([1,2,3,4])', sumOfArray([1,2,3,4]) );
const input = [1,2,3,4] const theFunctionYouWannaWrite = (acc, v) => { acc.push(v + (acc[acc.length - 1] || 0)) return acc; } const output = input.reduce(theFunctionYouWannaWrite, []) console.log(output)
if you want to use it with for
如果你想将它与
for
一起使用
const input = [1,2,3,4] const theFunctionYouWannaWrite = (acc, v) => { acc.push(v + (acc[acc.length - 1] || 0)) return acc; } function sumOfArray(nums) { var output = []; for(let i = 0 ; i < nums.length ; i++) { theFunctionYouWannaWrite(output, nums[i]) } return output; }; console.log(sumOfArray(input))
Just add first item in array initialization and everything works fine.只需在数组初始化中添加第一项,一切正常。
function sumOfArray(nums) { var output = [nums[0]]; // tip: initialize like let output = [nums?.[0] ?? 0]; for(let i = 1 ; i < nums.length ; i++) { nums[i] = nums[i] + nums[i-1]; output.push(nums[i]); } return output; }; console.log( 'calling sumOfArray([1,2,3,4])', sumOfArray([1,2,3,4]) );
let sum = 0, nums = [1, 2, 3, 4], res = []; nums.forEach((item, index, arr) => { sum += arr[index]; res.push(sum); }); console.log(res);
You can do it using Array.prototype.reduce .您可以使用Array.prototype.reduce来完成。
function sumOfArray(nums) { return nums.reduce((s, n) => (s.push((s.at(-1) ?? 0) + n), s), []); } console.log(sumOfArray([1, 2, 3, 4]));
And the problem with your solution is that you need start the loop from index 0
and check if the i-1
th index is valid using either ??
您的解决方案的问题是您需要从索引
0
开始循环并检查第i-1
个索引是否有效??
or ||
或
||
. .
function sumOfArray(nums) { const output = []; for (let i = 0; i < nums.length; i++) { nums[i] = nums[i] + (nums[i - 1] ?? 0); output.push(nums[i]); } return output; } console.log(sumOfArray([1, 2, 3, 4]));
Other relevant documentations:其他相关文件:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.