如何使用 Javascript 添加 n 个值

How to add n number of values using Javascript

我在这里有一个疑问,我需要传递n个值作为参数并使用Javascript计算它的总和。我在下面解释一些示例代码。

function add(a,b,c) {
  return a+b+c;
}



var data =add(5,6,7);

console.log(data)

这里我只向函数传递了 3 个参数,但我需要将 n 个参数传递给函数,就像在函数内部一样,它知道有多少值作为参数传递,最终我需要总和 return它。

正如@slappy 所说,您可以获得数组形式的参数

function add(...numbers){
  // Values reach as array
  console.log(numbers)
  // Here you should use array inner functions
  return numbers.reduce((sum,value) => sum+value, 0)
}

let data = add(5,6,7);
console.log(data)

如果你想以像

这样的函数式方式编写它,你可以减少它以求和
function add(...numbers) {
  return numbers.reduce((acc,no) => return acc + no),0);
}

或者通过使用 arguments 关键字知道它仅在函数是普通函数而不是箭头函数时可用。 这是参考

另外,arguments 不是一个数组,它是一个类似数组的数组,如果你检查了 typeof arguments,它会给你对象。