两者都使用 ...,但方向相反:spread 将一个集合展开为单个项;rest 将项收集到单个 array/object。
Spread — 展开
js
const a = [1, 2], b = [3, 4];
const merged = [...a, ...b]; // [1, 2, 3, 4]
const copy = [...a]; // shallow copy
const obj = { ...user, active: true }; // copy object + override/add a field
Math.max(...[1, , ]);
Rest — 收集
js
function sum(...nums) { // gather all args into an array
return nums.reduce((a, n) => a + n, 0);
}
sum(1, 2, 3); // 6
[first, ...others] = [, , ];
{ id, ...rest } = user;
一个关键细节:spread 是浅拷贝
js
const original = { user: { name: "Ann" } };
const copy = { ...original };
copy.user.name = "Bob"; // ⚠️ also changes original.user.name — nested object is SHARED
Spread 仅复制顶层;嵌套对象仍然是共享引用。对于状态更新,你通常只改变顶层,这没问题,但要注意深层结构。
为什么这很重要
Spread 是在 React/Redux 中进行不可变更新(复制 + 更改)的标准方式,rest 使可变参数函数和"抓取剩余项"解构变得简洁。
