展开运算符 ...
- 什么是展开运算符...
- 展开数组
- 作为函数参数
- 复制数组
- 合并数组
- 展开对象(在某些 JavaScript 版本中)
- 注意事项
什么是展开运算符…
展开运算符(Spread Operator)是 JavaScript 中用于展开可迭代对象(如数组、字符串、对象等)的语法。它提供了一种简洁的方式,可以将可迭代对象展开成多个元素,用于传递函数参数、数组字面量、对象字面量等。
展开数组
const numbers = [1, 2, 3];
const expandedNumbers = [...numbers, 4, 5]; // 展开数组并添加额外的元素
console.log(expandedNumbers); // 输出: [1, 2, 3, 4, 5]
作为函数参数
const numbers = [1, 2, 3];// 将数组中的元素作为参数传递给函数
function sum(a, b, c) {return a + b + c;
}const result = sum(...numbers); // 展开数组作为函数参数
console.log(result); // 输出: 6
复制数组
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray]; // 复制数组
console.log(copiedArray); // 输出: [1, 2, 3]
合并数组
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];const mergedArray = [...arr1, ...arr2]; // 合并两个数组
console.log(mergedArray); // 输出: [1, 2, 3, 4, 5, 6]
展开对象(在某些 JavaScript 版本中)
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // 展开对象并添加额外的属性
console.log(obj2); // 输出: { a: 1, b: 2, c: 3 }
注意事项
- 展开运算符只能用于可迭代对象。
- 在对象中展开运算符仅在某些 JavaScript 版本中受支持(如 ES2018/ES9 及更高版本)。
展开运算符为 JavaScript 中的数据操作提供了便捷的方式,使得处理数组和对象更加灵活和简洁。