首页 > 解决方案 > Rest Parameter 相对于数组类型参数有什么好处?

问题描述

是否有任何特定用例只能通过使用 Rest 参数而不是使用数组类型参数来实现?

function add1(...args) {
  let result = 0;

  for (let arg of args) result += arg;

  return result
}

function add2(args) {
  let result = 0;

  for (let arg of args) result += arg;

  return result
}

console.log(add1(1,2,3)); // 6
console.log(add2([1,2,3])); // 6

标签: javascript

解决方案


如果您希望将参数作为类数组对象或可迭代对象传递,则可以将数组用作输入,如果您希望将元素用作参数,则必须使用其余参数。

使用第一种方法的缺点是一些数组方法只支持可迭代。所以你必须去定制功能。

这取决于函数参数。让我们Math.max举个例子。

const numbers = [1, 3, 4]

Math.max(numbers) //output will be NaN

Math.max(...numbers) //output will be 4. More convenient than passing an array to the function on integers


推荐阅读