J 筆記 - Spread with Array

5 Use Case of Spread with Array

這篇將介紹,常用的 Spread 在陣列中的五種情況,可以拿來複製、合併或者是作轉換為陣列。首先,當然要先來了解 ES6 的 ... Spread 代表是什麼?還有它的特性。

Understanding Spread

1
2
3
4
5
6
7
8
9
10
11
function sum(x, y, z) {
return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));
// expected output: 6

MDN: Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Spread = Destructuring assignment?

什麼意思呢?其實,除了解構賦值之外,舉個例子像是, Spread 會把現在 Array 拿掉,然後再把裡面包住的東西放到另一個 Array 中。

1
2
3
4
5
6
7
8
[
...[1, 2, 3] // ... > []
]

/* 拿掉包住 [1, 2, 3] 的 Array */
[
1, 2, 3
]

Array Manipulation

  1. Use Spread for Merging Array

如果有兩個陣列需要把他合成一個,或許之前會是這樣子做,但會有一點瑕疵…

1
2
3
4
5
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

const merge = [array1, array2];
// [ [1, 2, 3], [4, 5, 6] ]

Spread 來做的話

1
2
3
4
5
const spread_merge = [
...array1,
...array2
];
// [1, 2, 3, 4, 5, 6]
  1. Clone Array

這部分在之前的系列筆記中其實已經大致上都有說到過,如果還沒有看過的可以去看一下 Clone an Array。另外,還有這一篇就在更複雜一些 Deep Clone Array

其中的觀念在,會不會影響到原本被複製的陣列,什麼時候是 Pass by reference、什麼時候是 Pass by value 而什麼情況下又會出現 JS 獨有的 Pass by sharing 呢?

1
2
3
4
5
const original = ['zero', 'one'];
const newArray = original;

original; // ['zero', 'one']
newArray; // ['zero', 'one']

看起來沒什麼問題,但如果只要改新陣列裡面的元素時,原本的陣列也會被更動了…

1
2
3
4
5
6
7
newArray[1] = '💩';

newArray;
// ['zero', '💩']

original;
// ['zero', '💩']...

Cloning Array the Right Way

1
2
3
4
5
6
7
8
9
const original = ['zero', 'one'];
const newArray = [...original];

newArray[1] = '💩';

newArray;
// ['zero', '💩']
original;
// ['zero', 'one']
  1. Iterables to Array

字串的部分就很好理解,也沒有什麼其他多變的情況…

1
2
3
4
5
6
const string = 'hi';

const array = [...string];

array;
// [ 'h' , 'i' ]
  1. Set to Array

The Set object lets you store unique values of any type, whether primitive values or object references.

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set’s collection.

1
2
3
4
5
6
7
8
9
const set = new Set([1, 2, 3]);

set;
// Set(3) {1, 2, 3}

const array = [...set];

array;
// [1, 2, 3]
  1. Node List to Array
1
2
3
4
5
6
7
8
const nodeList = document.querySelectorAll('p');

nodeList;
// [p, p, p]

const array = [...nodeList];

array;

參考資料