ES6扩展运算符的实战案例

90 阅读1分钟

以下是一些ES6扩展运算符的实战案例:

  1. 合并数组:
复制代码
const arr1 = [1, 2];
const arr2 = [3, 4];

const newArr = [...arr1, ...arr2];
console.log(newArr); // 输出:[1, 2, 3, 4]
  1. 复制数组或对象:
复制代码
const arr = [1, 2, 3];
const copyArr = [...arr];
console.log(copyArr); // 输出:[1, 2, 3]

const person = {
  name: 'Alice',
  age: 30
};
const copyPerson = { ...person };
console.log(copyPerson); // 输出:{ name: 'Alice', age: 30 }
  1. 将字符串转换为字符数组:
复制代码
const str = 'hello';
const arr = [...str];
console.log(arr); // 输出:['h', 'e', 'l', 'l', 'o']
  1. 函数参数传递:
复制代码
function sum(a, b, c) {
  return a + b + c;
}

const arr = [1, 2, 3];
const result = sum(...arr);
console.log(result); // 输出:6
  1. 从对象中提取属性:
复制代码
const person = {
  name: 'Bob',
  age: 25,
  address: {
    city: 'New York',
    state: 'NY'
  }
};

const { name, ...rest } = person;
console.log(rest); // 输出:{ age: 25, address: { city: 'New York', state: 'NY' } }

这些都是ES6扩展运算符的实战案例,它们可以在代码中提高可读性和减少冗余代码。