英文:
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) => acc + cur);
console.log(res)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论