在 JavaScript 中将数组数字转换为累加和数组
我们有这样一个数组数字 −
const arr = [1, 1, 5, 2, -4, 6, 10];
我们需要编写一个函数,该函数返回一个新数组,该数组大小相同,但每个元素都是此点之前的各个元素之和。
因此,输出应如下所示 −
const output = [1, 2, 7, 9, 5, 11, 21];
因此,让我们编写函数 partialSum(),
此函数的完整代码如下 −
const arr = [1, 1, 5, 2, -4, 6, 10];
const partialSum = (arr) => {
const output = [];
arr.forEach((num, index) => {
if(index === 0){
output[index] = num;
}else{
output[index] = num + output[index - 1];
}
});
return output;
};
console.log(partialSum(arr));在这里,我们遍历了数组并持续为输出数组的元素分配一个新值,该值是当前数字及其前驱之和。
控制台中代码的输出将为 −
[ 1, 2, 7, 9, 5, 11, 21 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP