概念
扩展运算符(Spread Operator)是 ES6 中引入的一种语法,使用三个点(...
)表示。
主要功能是将数组或类数组对象展开成一系列用逗号隔开的值。
基本用法
1、数组复制
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
console.log(arr2); // [1, 2, 3]
2、数组合并
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
const arr3 = [...arr1,...arr2];
console.log(arr3); //[1, 2, 3, 1, 2, 3]
3、函数传递
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6
4、解构赋值
const arr = [1, 2, 3, 4];
const [first, ...rest] = arr;
console.log(first); // 1
console.log(rest); // [2, 3, 4]
5、字符串转数组
const str = 'hello';
const charArray = [...str]; // ['h', 'e', 'l', 'l', 'o']