How to use the spread operator (...)

Learn how to use the three-dot operator (...) is also known as spread operator.

spread operator

JavaScript's spread operator (...) Can expand an iterable object (such as an array) into more elements.

This allows us to quickly copy all or part of an existing array to another array:

instance

Use the spread operator in JavaScript to merge two arrays

const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];

try it yourself

The spread operator is often used to extract the required parts from an array:

instance

Assign the first and second items of the numbers array to variables, and put the rest into another array:

const numbers = [1, 2, 3, 4, 5, 6];
const [one, two, ...rest] = numbers;

try it yourself

We can also use the spread operator on objects:

instance

const myVehicle = {
  brand: 'Ford',
  model: 'Mustang',
  color: 'red'
}
const updateMyVehicle = {
  type: 'car',
  year: 2021,
  color: 'yellow'
}
const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}

try it yourself

Please note that unmatched properties have been merged, but matching properties color an object that was entered last updateMyVehicle 覆盖了。最终的颜色现在是黄色。

相关页面

教程:JavaScript ES6