学习扩展运算符

发布时间 2023-03-29 00:12:49作者: Himmelbleu

扩展运算符只能使用在可迭代对象(数组、字符串、Map、Set)。扩展运算符对这些可迭代对象进行展开。

展开数组

const arr = [1, 2, 3, 4];
console.log(...arr); // 1 2 3 4

合并数组

可以直接合并两个数组,而不需要使用 Array.concat API 对两个数组进行合并。

const arr = [1, 2];
const newArr = [...arr, 3, 4];
console.log(newArr); // [1, 2, 3, 4]

拷贝数组

const arr = [1, 2, 3];
const newArr = [...arr];
newArr.push(4); // newArr 此时变成 [1, 2, 3, 4]

拷贝之后的数组与原数组没有关系,两者之间不会影响。

展开对象

const obj = {
  x: 1,
  y: 2,
};

console.log(...obj); // error

// 正确的
console.log({ ...obj }) // {x: 1, y: 2}

合并对象

将已有对象的所有可枚举属性拷贝到新构造的对象中。

const obj1 = { x: 1 };
const obj2 = { y: 2 };
const newObj = { ...obj1, ...obj2 };
console.log(newObj); // {x: 1, y: 2}

拷贝对象(浅拷贝)

得到一个新的对象,obj1 和 obj2 的引用不是同一个。

const obj1 = { x: 1 };
const obj2 = { ...obj1 };

console.log(obj1 === obj2); // false

用在函数中

在 TypeScript 中,给函数传递扩展数组需要确保数组是元组类型:

// example1
function fn(x: number, y: number, z: number) {}
const args: [number, number, number] = [0, 1, 2];
fn(...args);

// example2
function fn2(v: number, w: number, x: number, y: number, z: number) {}
const args1: [number, number] = [0, 1];
const args2: [number] = [3];
fn2(-1, ...args1, 2, ...args2);

在 JavaScript 中,直接扩展数组:

// example1
function fn(x, y, z) {}
const args = [0, 1, 2];
fn(...args);

// example2
function fn2(v, w, x, y, z) {}
const args1 = [0, 1];
const args2 = [3];
fn2(-1, ...args1, 2, ...args2);