Rest 参数允许你将不定数量的参数表示为一个数组。
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15
Rest 参数必须是函数参数的最后一个参数
// 错误示例
function fn(a, ...b, c) {} // SyntaxError
Rest 参数与 arguments
对象的区别:
arguments
是类数组对象,需要转换为数组才能使用数组方法可以与解构赋值一起使用
const [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1
console.log(rest); // [2, 3, 4]
Spread 语法允许一个可迭代对象(如数组或字符串)在需要多个参数或元素的地方展开。
函数调用中的使用
const numbers = [1, 2, 3];
console.log(Math.max(...numbers)); // 3
数组字面量中的使用
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
对象字面量中的使用 (ES2018+)
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
可以用于浅拷贝数组或对象
const original = [1, 2, 3];
const copy = [...original];
可以合并多个数组或对象
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2]; // [1, 2, 3, 4]
可以将字符串转换为字符数组
const str = "hello";
const chars = [...str]; // ["h", "e", "l", "l", "o"]
特性 | Rest 参数 | Spread 语法 |
---|---|---|
位置 | 函数参数定义时使用 | 函数调用或数组/对象字面量中使用 |
作用 | 将多个参数收集为数组 | 将数组/对象展开为多个元素 |
符号位置 | 在参数定义时使用 ... |
在表达式或字面量中使用 ... |
使用场景 | 函数参数处理 | 数组/对象操作、函数调用传参 |
移除数组中的第一个元素
const [first, ...rest] = [1, 2, 3, 4];
console.log(rest); // [2, 3, 4]
合并对象并覆盖属性
const defaults = { color: 'red', size: 'medium' };
const userSettings = { color: 'blue' };
const finalSettings = { ...defaults, ...userSettings }; // { color: 'blue', size: 'medium' }
将 NodeList 转换为数组
const divs = [...document.querySelectorAll('div')];
函数柯里化
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
} else {
return function(...args2) {
return curried.apply(this, args.concat(args2));
}
}
};
}
掌握 Rest 参数和 Spread 语法可以大大简化 JavaScript 代码,使其更加简洁和易读。