扩展运算符(...):拆箱神器
作用:将数组或对象“拆包”成独立元素,类似拆快递盒直接取物品
1、数组场景
合并数组(替代 concat)
const fruits = ["🍎", "🍌"];
const veggies = ["🥕", "🥦"];
const food = [...fruits, ...veggies]; // ["🍎", "🍌", "🥕", "🥦"]
复制数组(浅拷贝)
const arr1 = [1, 2, 3];
const arr2 = [...arr1]; // 独立新数组,修改 arr2 不影响 arr1
函数传参(替代 apply)
function add(a, b, c) { return a + b + c; }
const nums = [1, 2, 3];
add(...nums); // 6(直接拆包传入)
2、对象场景
合并对象(浅层属性合并)
const user = { name: "小明" };
const info = { age: 18 };
const profile = { ...user, ...info }; // { name: "小明", age: 18 }
对象浅拷贝
const obj1 = { a: 1 };
const obj2 = { ...obj1 }; // 独立新对象
3、特殊用法
字符串转数组
const str = "hello";
const chars = [...str]; // ["h", "e", "l", "l", "o"]
Rest 参数(...):打包工具
作用:将零散元素“打包”成数组,类似把散落的物品收进箱子。
1、函数参数打包
收集剩余参数(替代 arguments)
function sum(...nums) {
return nums.reduce((total, num) => total + num, 0);
}
sum(1, 2, 3); // 6(nums = [1, 2, 3])
配合解构使用
const [first, ...others] = [1, 2, 3, 4];
console.log(others); // [2, 3, 4]
2、强制规则
必须放在参数末尾
function demo(a, b, ...rest) {} // ✅ 正确
function error(...rest, c) {} // ❌ 报错!
对比两者差异
| 特性 | 扩展运算符 | Rest 参数 |
|---|---|---|
| 符号 | ... | ... |
| 作用方向 | 拆包(展开数据) | 打包(收集数据) |
| 常用场景 | 数组合并、对象拷贝、函数传参 | 收集剩余参数、解构剩余元素 |
| 位置限制 | 无位置限制 | 必须位于函数参数末尾 |
| 典型比喻 | 拆快递箱 | 收快递箱 |
一些常见的使用场景
动态参数函数
function logItems(type, ...items) {
console.log(`${type}:`, ...items); // 扩展运算符输出
}
logItems("水果", "🍎", "🍌"); // 水果: 🍎 🍌
合并对象并覆盖属性
const defaults = { color: "red", size: "M" };
const custom = { size: "L" };
const result = { ...defaults, ...custom }; // { color: "red", size: "L" }
箭头函数替代 arguments
const showArgs = (...args) => console.log(args);
showArgs(1, 2); // [1, 2](箭头函数无 arguments 对象)
牢记
扩展运算符和 Rest 参数是 ES6 的“镜像双生子”——一个负责拆,一个负责收