ES6 中 rest 参数

文章类型:ES6

发布者:hp

发布时间:2025-02-28

一:定义

1:语法:使用...变量名,且必须作为函数参数的最后一个形参

function demo(a, b, ...args) { /* args 为数组 */ }

2:特性:rest参数是真正的数组实例,可直接调用数组方法

二:优势

1:替换arguments对象

// ES5 写法
function sortNumbers() { return Array.prototype.slice.call(arguments).sort(); }
// ES6 写法
const sortNumbers = (...nums) => nums.sort();

2:提升代码可读性,显式声明参数收集逻辑,明确函数意图

三:注意点

1:参数位置限制:必须位于参数列表末尾

2:不影响函数length属性:函数的length属性仅统计非rest参数的形参数量

(function(a, ...b) {}).length // 结果为 1(仅计算 a)

四:拓展

(1):跟扩展运算符对比

rest参数=>用于函数定义时,将离散参数合并为数组(参数收集)

扩展运算符=>用于函数调用时,将数组展开为离散参数(参数拆分)

// rest 参数(收集)
function sum(...nums) { return nums.reduce((a, b) => a + b); }
// 扩展运算符(拆分)
const arr = [1, 2, 3];
sum(...arr); // 等效于 sum(1, 2, 3)

(2)跟arguments对象相比

rest参数=>仅收集函数形参中未显示声明的剩余参数

arguments对象=>包含所有传递给函数的参数

function demo(a, b, ...args) {}  
function demo(a, b) { console.log(arguments) }  
demo(1, 2, 3); // arguments 包含 [1, 2, 3]

五:总结

1:rest参数通过语法层面的优化,解决传统arguments对象在参数处理中的冗杂问题

2:提供了更直观、安全的动态参数处理方式,提升代码可维护性和功能灵活性