1. 程式人生 > 其它 >8.Es6-擴充套件運算子

8.Es6-擴充套件運算子

擴充套件運算子(spread)是三個點(...)。它好比 rest 引數的逆運算,將一個數組轉為用逗號分隔的引數序列。

console.log(...[1, 2, 3])
// 1 2 3

console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5

[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]

合併陣列

擴充套件運算子提供了數組合並的新寫法。

const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 
= ['d', 'e']; // ES5 的合併陣列 arr1.concat(arr2, arr3); // [ 'a', 'b', 'c', 'd', 'e' ] // ES6 的合併陣列 [...arr1, ...arr2, ...arr3] // [ 'a', 'b', 'c', 'd', 'e' ]

不過,這兩種方法都是淺拷貝,使用的時候需要注意。

const a1 = [{ foo: 1 }];
const a2 = [{ bar: 2 }];

const a3 = a1.concat(a2);
const a4 = [...a1, ...a2];

a3[0] === a1[0] // true
a4[0] === a1[0] // true

上面程式碼中,a3a4是用兩種不同方法合併而成的新陣列,但是它們的成員都是對原陣列成員的引用,這就是淺拷貝。如果修改了引用指向的值,會同步反映到新陣列。

const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest  // [2, 3, 4, 5]

const [first, ...rest] = [];
first // undefined
rest  // []

const [first, ...rest] = ["foo"];
first  // "foo"
rest   // []

如果將擴充套件運算子用於陣列賦值,只能放在引數的最後一位,否則會報錯。

const [...butLast, last] = [1, 2, 3, 4, 5];
// 報錯

const [first, ...middle, last] = [1, 2, 3, 4, 5];
// 報錯

字串

擴充套件運算子還可以將字串轉為真正的陣列。

[...'hello']
// [ "h", "e", "l", "l", "o" ]