扩展运算符

概述

在JavaScript中,扩展运算符(Spread operator)是一种方便的语法,它允许一个表达式在某些地方展开成多个元素(对于数组)或多个键值对(对于对象)。扩展运算符使用三个连续的点(...)来表示。

用途

数组中的扩展运算符

在数组中,扩展运算符可以将一个数组展开成其包含的元素,并将这些元素插入到另一个数组中,或者用于函数调用时传递数组元素作为单独的参数。

  1. 合并数组
1
2
3
4
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];
console.log(combined); // 输出: [1, 2, 3, 4]
  1. 函数调用时传递数组元素
1
2
3
4
5
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 输出: 6
  1. 复制数组
1
2
3
4
5
const arr1 = [11, 22, 33]
const arr2 = arr1
arr2.push(44)
console.log(arr1)
console.log(arr2)

alt text{: height=75%, width=75%}

arr2和arr1之间的赋值是引用赋值,所以修改一个变量会影响另外一个变量。

1
2
3
4
5
const arr1 = [11, 22, 33]
const arr2 = [...arr1]
arr2.push(44)
console.log(arr1)
console.log(arr2)

alt text{: height=75%, width=75%}

对象中的扩展运算符

在ES2018及更高版本中,扩展运算符也可以用于对象,但它与数组的行为有所不同。对象扩展运算符用于将一个对象的所有可枚举自有属性,作为独立的属性复制到另一个对象中。

  1. 合并对象
1
2
3
4
5
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const combined = { ...obj1, ...obj2 };
console.log(combined); // 输出: { a: 1, b: 3, c: 4 }
// 注意:如果属性名相同,后面的对象会覆盖前面的对象中的属性值。
  1. 复制对象
1
2
3
4
5
6
7
8
9
10
11
const obj1 = {
id: 10001,
name: 'ycq',
age: 9
}
console.log(obj1)
const obj2 = {
...obj1
}
obj2.age = 10
console.log(obj2)

alt text{: height=75%, width=75%}