javascript - 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
解决方案
如果您希望将参数作为类数组对象或可迭代对象传递,则可以将数组用作输入,如果您希望将元素用作参数,则必须使用其余参数。
使用第一种方法的缺点是一些数组方法只支持可迭代。所以你必须去定制功能。
这取决于函数参数。让我们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
推荐阅读
- c# - 静态类中的依赖注入
- javascript - 如何在 React 中实现上一个和下一个按钮?
- c++ - nlohmann 和复制地图
- excel - 数据透视表项目 - 避免使用许多导致 Excel 崩溃的 INDEX 和 MATCH 函数
- node.js - 等待KafkaJS中的领导选举
- apache-kafka - 如何定期而不是连续地读取/轮询 kafka 消息
- html - 如何为 ID 中的类自定义 CSS
- css - 如何将 CSS 从“::before”选择器移动到 React?
- java - Spring Boot 卡夫卡监听器
- sql - SQL Server - 计算销售概览的每周目标值与实际值