创建具有累积模式的循环函数

问题描述 投票:1回答:3

我对学习JavaScript并不陌生,需要帮助来创建一个函数,该函数执行带有通过数组的累积模式的for循环。

到目前为止,我所写的内容将无错误运行,但无法在整个数组“目标”中执行该功能

function totalGoals (goals, total) {
    for (i=0, g=goals.length; i<g; i++)
        return (total + goals[i])
}

totalGoals([ 1, 2, 3], 1)

我做错了什么?我希望函数在“目标”操作中累积每个值。

javascript arrays function for-loop accumulator
3个回答
1
投票

这是您要寻找的吗?

function totalGoals (goals, total) {
  for (let i = 0; i < goals.length; i++) {
    total += goals[i]
  }
  return total
}
const total = totalGoals([1, 2, 3], 1)
console.log(total)

1
投票

内置数组.reduce方法

console.log([1, 2, 3].reduce((a, b) => a + b, 1));

0
投票

以下代码对数组中的数字求和。 for循环枚举数组中的项,并且每次循环时,都会更新累加器变量。

function sum(arr) {
 let acc = 0
 for (let i = 0; i < arr.length; i++) {
   acc += arr[i]
 }
 return acc
}
const result = sum([1, 2, 3])
console.log(result)
© www.soinside.com 2019 - 2024. All rights reserved.