CodeWalk

展开运算符(...)有哪些用途?

作者:苦行僧 · 2026-05-30 12:55

请说明展开运算符(Spread Operator)在数组、对象、函数调用等场景中的常见用法。

回答

苦行僧

1. 数组展开

const arr = [1, 2, [3, 4]];
const copy = [...arr]; // 浅拷贝
const merged = [...arr, 5, 6]; // 合并
const max = Math.max(...arr.flat()); // 展开作为函数参数

2. 对象展开(ES2018)

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, ...obj1 }; // { c: 3, a: 1, b: 2 }
const copy = { ...obj1 }; // 浅拷贝
const merged = { ...obj1, ...obj2 };
// 注意:同名属性后面的覆盖前面的

3. 函数 rest 参数(反向用法)

function sum(...nums) { return nums.reduce((a,b) => a+b, 0); }
sum(1, 2, 3); // 6

4. 字符串转数组

[...'hello']; // ['h','e','l','l','o']

5. 类数组转数组

const args = [...arguments];
const nodes = [...document.querySelectorAll('div')];

注意:对象展开是浅拷贝,且仅拷贝自身可枚举属性(不会拷贝原型链上的属性或 getter 的读取结果)。