三个点-剩余-省略号拓展运算符-展开运算符

梗概:

  • 扩展运算符(spread)是三个点(...)。它好比 rest 参数的逆运算,用于将一个数组或类数组对象转换为用逗号分隔的值序列。
  • 可用于数组、类数组、字符串对象

浅克隆还是深克隆

浅拷贝

实例:

之一

它的基本用法是拆解数组和字符串。

const array = [1, 2, 3, 4];
console.log(...array); // 1 2 3 4
const str = "string";
console.log(...str); // s t r i n g

在上面的代码中数组类型变量 array 和字符串类型变量 str 在经过扩展运算符的处理后,得到的都是单独的值序列。

之一

child::

const original = { a: 1, b: { c: 2 } };
const shallowCopy = { ...original };
 
shallowCopy.a = 3;
shallowCopy.b.c = 4;
console.log(original);// { a: 1, b: { c: 4 } }
console.log(shallowCopy);// { a: 3, b: { c: 4 } }
指向原始笔记的链接

应用:

1. 扩展运算符代替 concat() 函数合并数组

在 ES5 中,合并数组时,我们会使用 concat() 函数,写法如下:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
console.log(arr1.concat(arr2)); // [ 1, 2, 3, 4, 5, 6 ]

如果使用扩展运算符,写法如下: console.log([...arr1, ...arr2]); // [ 1, 2, 3, 4, 5, 6 ]

2. 扩展运算符转换 Set,得到去重的数组

Set 具有自动的去重性质,我们可以再次使用扩展运算符将 Set 结构转换成数组。

let arr = [1, 2, 4, 6, 2, 7, 4];
console.log([...new Set(arr)]); // [ 1, 2, 4, 6, 7 ]

详解链接:

child::9. 数组的扩展 - 扩展运算符 - 《阮一峰 ECMAScript 6 (ES6) 标准入门教程 第三版》 - 书栈网 · BookStack