计算数组的总和

时间:2018-11-20 09:47:54

标签: javascript arrays sum

我使用以下JavaScript创建了一个数组:

for (i = 0; i < numOfPeriodsCost; i++) {
    esclatedPrice *= (1 + annualElecIncrease)
    rateArray.push(esclatedPrice);
    annualCostA = consumptionA * rateArray[i]
    console.log("annualCostA= " + annualCostA);
}

对于上下文:

var numOfPeriodsCost = 10;
var annualElecIncrease = 0.1;
var consumptionA = 520;

控制台会为AnnualCostA记录以下内容:

enter image description here

如何进一步执行此步骤并计算数组的总和?

谢谢

7 个答案:

答案 0 :(得分:1)

在循环中,只需添加一个变量sum,它将在每次迭代中添加annualCostA的值,如下所示:

var sum = 0;
for (i = 0; i < numOfPeriodsCost; i++) {
    esclatedPrice *= (1 + annualElecIncrease)
    rateArray.push(esclatedPrice);
    annualCostA = consumptionA * rateArray[i]
    sum += annualCostA // add the annualCostA value in each iteration 
    console.log("annualCostA= " + annualCostA);
}
console.log(sum); //total sum

答案 1 :(得分:1)

您可以使用Array.prototype.reduce()

var sumOfRateArray = rateArray.reduce((a, c) => a + c, 0);

代码:

const rateArray = [12.100000000000001,13.310000000000002,14.641000000000004,16.105100000000004,17.715610000000005,19.487171000000007,21.43588810000001,23.579476910000015,25.937424601000018];
const sumOfRateArray = rateArray.reduce((a, c) => a + c, 0);

console.log(sumOfRateArray);

答案 2 :(得分:0)

在循环let sum=0;之前添加一个sum变量

将要求和的元素添加到循环sum+= your_element;

打印结果console.log("Sum= "+sum);

答案 3 :(得分:0)

在循环后的rateArray变量上使用Array.prototype.reduce()

var rateArray = [
    936,
    1029.6,
    1132.56
];

var arraySum = rateArray.reduce((total, e) => total + e);

console.log(arraySum)

答案 4 :(得分:0)

var numOfPeriodsCost = 10;
var annualElecIncrease = 0.1;
var consumptionA = 520;

let sum = 0;

for (i = 0; i < numOfPeriodsCost; i++) {
  esclatedPrice *= (1 + annualElecIncrease);
  rateArray.push(esclatedPrice);
  annualCostA = consumptionA * rateArray[i]
  console.log("annualCostA= " + annualCostA);
  sum += annualCostA;
}

console.log('sum', sum);

答案 5 :(得分:0)

以下是forEach方法:

let numbers = [1, 2, 3, 4];
let sum = 0;
numbers.forEach((item, index)=>{sum= sum + item;});
document.write("Sum: " + sum);

测试:link

文档:link

答案 6 :(得分:0)

我认为您的年度计算有问题,应该是consumption + (years*increase*consumption)吗?

您可以将0-numOfPeriodsCost数组映射到年度成本,并将其减少到包含该年以及该年之前的总成本的数组。然后将这些值映射到包含合计和年份的对象中:

const numOfPeriodsCost = 10;
const annualElecIncrease = 0.1;
const consumptionA = 520;

console.log(
  [...new Array(numOfPeriodsCost)]
    .map(
      (_, period) =>
        consumptionA +
        period * annualElecIncrease * consumptionA,
    )
    .reduce(
      ([sum, result], item) => [
        sum + item,
        result.concat([[sum + item, item]]),
      ],
      [0, []],
    )[1]
    .map(([total, year]) => ({ total, year })),
);