javascript - 如何使数组相加?

标签 javascript arrays math

我想添加一个数组相加。

假设有一个数组 [7, 1, 21, 70]

在数组索引为 0 的情况下,它只是 7。在数组索引为 1 的情况下,我希望它是 7 + 1 (8)。数组索引 2, 7 + 1 + 21 (29)。数组索引 3 7 + 1 + 21 + 70 (99)。

这是我当前的代码:

var pot = {
  'id': 1,
  'name': ['stalin', 'hitler', 'mao', 'kim jong-il'],
  'amount': [50, 10, 150, 500],
  'percentages': new Array()
}

var random = Math.random()*100;
var random = String(random).split(".")[0];
console.log(random);

function potTotal(amounts) {
  var sum = 0;
  for (var key in amounts) {
    sum += pot['amount'][key];
  }
  return sum;
}

function potPercentage(total, amounts) {
  for (var key in amounts) {
    var percentage = amounts[key] / total * 100;
    var percentage = String(percentage).split(".")[0];
    var percentage = Number(percentage);
    pot['percentages'].push(percentage);
  }
}

potPercentage(potTotal(pot['amount']), pot['amount']);

function ranging(total, percentages) {
  console.log(percentages);
  for(var i = 0; percentages < i; i++) {
    console.log(percentages[i]);
  }
}
//[7, 1, 21, 70]
ranging(random, pot['percentages']);

for (var key in pot['percentages']) {
  console.log(key);
  console.log(pot['percentages'][key]);
}

返回结果:

69
[ 7, 1, 21, 70 ]
0
7
1
1
2
21
3
70

最佳答案

reduce 是为执行此类任务而定义的函数。

const arr = [7, 1, 21, 70].reduce((acc, el, i) => [...acc, (acc[i-1] || 0) + el], []);
console.log(arr);

关于javascript - 如何使数组相加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51223401/

相关文章:

Javascript:根据包含字符串日期的子数组元素对数组进行排序

c++ - 在 O(1) 空间和 O(n) 时间的数组中将相同类型的元素组合在一起

javascript - 如何从 JavaScript 数组生成 3x3 HTML 表

javascript - 数组中的 indexOf 行为不正确

javascript - VeeValidate 'required_if:' 规则

javascript - 使用 javascript 和 less css 调试 onMouseOver 和 onMouseOut

java - 文件没有值

c - 编辑用户输入而不是内部输入的脚本

math - ^ (XOR) 运算符有什么作用?

iphone - iPhone 游戏中最快的 C vector/矩阵数学库是什么?