返回

ES6 新特性——扩展运算符妙用无穷

前端

1. 扩展运算符在函数调用中的妙用

扩展运算符在函数调用中的妙用主要体现在将数组表达式或者字符串在语法层面展开,具体用法如下:

  • 将数组表达式展开
const numbers = [1, 2, 3, 4, 5];
console.log(Math.max(...numbers)); // 5
  • 将字符串展开
const str = 'Hello, World!';
console.log([...str]); // ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']

2. 扩展运算符在数组构造中的妙用

扩展运算符在数组构造中的妙用主要体现在以下三个方面:

  • 合并多个数组
const numbers1 = [1, 2, 3];
const numbers2 = [4, 5, 6];
const mergedArray = [...numbers1, ...numbers2]; // [1, 2, 3, 4, 5, 6]
  • 复制数组
const numbers = [1, 2, 3];
const copiedArray = [...numbers]; // [1, 2, 3]
  • 从数组中提取元素
const numbers = [1, 2, 3, 4, 5];
const extractedArray = [ ...numbers.slice(2, 4) ]; // [3, 4]

3. 扩展运算符在对象构造中的妙用

扩展运算符在对象构造中的妙用主要体现在将对象表达式按 key-value 方式展开,具体用法如下:

  • 合并多个对象
const obj1 = { name: 'John', age: 25 };
const obj2 = { city: 'New York' };
const mergedObject = { ...obj1, ...obj2 }; // { name: 'John', age: 25, city: 'New York' }
  • 复制对象
const obj = { name: 'John', age: 25 };
const copiedObject = { ...obj }; // { name: 'John', age: 25 }
  • 从对象中提取属性
const obj = { name: 'John', age: 25, city: 'New York' };
const extractedObject = { ...obj, name: undefined }; // { age: 25, city: 'New York' }

4. 扩展运算符的妙用场景

扩展运算符的妙用场景十分广泛,以下是几个常见的妙用场景:

  • 函数参数解构
function sum(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
}

const numbers = [1, 2, 3, 4, 5];
console.log(sum(...numbers)); // 15
  • 数组解构
const numbers = [1, 2, 3, 4, 5];
const [first, ...rest] = numbers;

console.log(first); // 1
console.log(rest); // [2, 3, 4, 5]
  • 对象解构
const person = {
  name: 'John',
  age: 25,
  city: 'New York'
};

const { name, ...rest } = person;

console.log(name); // John
console.log(rest); // { age: 25, city: 'New York' }

结语

扩展运算符是 ES6 中一项非常强大的特性,它在函数调用、数组构造和对象构造中都有着广泛的妙用场景。通过本文的介绍,相信大家已经对扩展运算符有了更深入的了解。希望大家能够在日常开发中熟练运用扩展运算符,从而提高开发效率和代码可读性。