Explanation of the spread operator... in ES6

The spread operator in ES6 ...can expand an array or array-like object into independent elements, making the code more concise and readable.

Specifically, the spread operator can be used in the following scenarios:

  1. Use in function parameters: use an array as a function parameter, use the spread operator to expand into independent elements and pass them into the function.

  2. Constructing a new array: When using an array literal to construct a new array, the elements in the existing array can be quickly merged into the new array through the spread operator.

  3. Generate a new object: Use the spread operator to combine multiple objects into a new object, or to extract some properties from an object to create a new object.

Here are a few common examples:

// 1. 函数参数
function sum(x, y, z) {
  return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6

// 2. 构造新数组
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]

// 3. 生成新对象
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 };
console.log(merged); // { a: 1, b: 2, c: 3, d: 4 }

// 从对象中提取部分属性创建新对象
const { a, b, ...rest } = merged;
console.log(a, b); // 1, 2
console.log(rest); // { c: 3, d: 4 }

Guess you like

Origin blog.csdn.net/zhtxilyj/article/details/130503756
Recommended