如何将数组用作函数的参数以将其元素相加?

huangapple go评论64阅读模式
英文:

How to use an array as an argument of a function to add its elements?

问题

我想使用一个数组作为函数的参数,对它们进行一些计算,但我不知道如何将数组的元素变成函数可以使用的变量。我正在使用JavaScript进行编程。

我刚开始学编程,所以我尝试尽可能简单,使用我掌握的基本概念。

let numbers = [m1, m2];

function sum(numbers) {
    let result = m1 + m2;
    return result;
}

console.log(numbers[2, 4].reduce(sum));
英文:

I want to use an array as the argument of a function to do some calculation with them, but I don't know how to make the elements of the array variables that the function can use. i am working on java.script .

I am starting programming so I try to make it as simple as possible with the basic concepts that I have

let numbers=[m1,m2]
 function sum( numbers){
       let result = m1+m2
      return (result);
 }

  console.log(numbers[2,4].reduce(sum))

答案1

得分: 1

以下是reduce的语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

以下是如何使用reduce来对JavaScript数组的元素求和的示例:

let numbers = [12, 23, 34];

function getSum(total, num) {
  return total + num;
}

console.log(numbers.reduce(getSum))

reduce将递归调用您创建的函数。num将代表传入的数组的一个元素。

英文:

Here is the syntax for reduce: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Here is an example of how you can use reduce to sum the elements of a javascript array:

let numbers = [12,23,34];

function getSum(total, num) {
return total + num;
}

console.log(numbers.reduce(getSum))

Reduce will recursively call the function you have created. Num will represent an element of the array being passed in.

答案2

得分: 0

No need to use a function for that, reduce() is enough for your needs.

acc 是累加器,它将在每次迭代中存储您的求和的总值。

cur 是当前值,在这种情况下,在第一次迭代中,您的当前值将是2,下一个将是4。

英文:

No need to use a function for that, reduce() is enough for your needs.

acc is the accumulator, it will store the total value of your sum in each iteration.

cur is the current value, in this case on the first iteration your current value will be 2 and the next one will be 4.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let numbers = [2, 4];
const res = numbers.reduce((acc, cur) =&gt; acc + cur);
console.log(res)

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月17日 23:39:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76706076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定