es6 ...展开语法

发布时间 2023-11-23 15:14:32作者: 酷酷的抖s

ES6中的...(展开)语法是一种可以将数组或对象展开为函数参数或数组字面量的语法。它通常用于函数调用或数组字面量的展开。

在函数调用中,...可以将一个数组展开为函数的参数列表。例如:

js复制代码
  function sum(a, b, c) {
  return a + b + c;
  }
   
  const numbers = [1, 2, 3];
  console.log(sum(...numbers)); // 输出:6

在这个例子中,我们将数组 numbers 展开为 sum 函数的参数列表,分别传入了 12 和 3

在数组字面量中,...可以将一个数组展开为另一个数组的元素。例如:

js复制代码
  const colors = ['red', 'green', 'blue'];
  const [firstColor, ...otherColors] = colors;
  console.log(firstColor); // 输出:red
  console.log(otherColors); // 输出:['green', 'blue']

在这个例子中,我们将数组 colors 展开为 firstColor 和 otherColors 的值,其中 firstColor 的值为 'red'otherColors 的值为 ['green', 'blue']

除了在数组和函数中使用展开语法,它还可以用于对象的解构赋值中。例如:

js复制代码
  const person = { name: 'Alice', age: 25 };
  const { name, ...otherProps } = person;
  console.log(name); // 输出:Alice
  console.log(otherProps); // 输出:{ age: 25 }

在这个例子中,我们将对象 person 展开为 name 和 otherProps 的值,其中 name 的值为 'Alice'otherProps 的值为 { age: 25 }