一、使用concat()方法合併數組
JavaScript中提供了一種簡單方便的方法來合併兩個數組 – concat()方法。concat()方法可以將兩個或多個數組合併為一個新的數組。
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let arr3 = arr1.concat(arr2); console.log(arr3); // [1, 2, 3, 4, 5, 6]
concat()方法可以接受任意數量的參數,並且可以合併不同類型的值。
let arr1 = [1, 2, 3]; let arr2 = ['a', 'b', 'c']; let arr3 = arr1.concat(arr2, 4, 5, 6); console.log(arr3); // [1, 2, 3, 'a', 'b', 'c', 4, 5, 6]
在合併對象數組時,也可以使用concat()方法。需要注意的是,concat()方法只能合併一維數組,如果要合併多維數組,則需要使用其他方法。
二、使用spread operator(…)操作符合併數組
使用spread operator(…)操作符可以將一個數組中的元素展開為獨立的值,並將它們插入到另一個數組中。這個操作符是ES6中新增的語法。
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let arr3 = [...arr1, ...arr2]; console.log(arr3); // [1, 2, 3, 4, 5, 6]
spread operator(…)操作符不僅可以用來合併數組,還可以用來將一個數組中的元素插入到另一個數組的中間位置。
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let arr3 = [7, 8, 9]; let arr4 = [...arr1, ...arr2, ...arr3]; console.log(arr4); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
三、使用push()和apply()方法合併數組
除了concat()方法和spread operator(…)操作符之外,還可以使用push()方法和apply()方法來合併數組。這種方式比較麻煩,但是在一些不支持spread operator(…)操作符的舊版本中,它仍然是一個實用的方法。
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; Array.prototype.push.apply(arr1, arr2); console.log(arr1); // [1, 2, 3, 4, 5, 6]
上面的代碼等同於下面的代碼:
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; arr1.push.apply(arr1, arr2); console.log(arr1); // [1, 2, 3, 4, 5, 6]
四、利用ES6的Array.from()方法合併數組
ES6還提供了另外一個方法Array.from(),可以將一個類數組對象或可迭代對象轉換為一個數組。這個方法也可以用來合併兩個數組。
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let arr3 = Array.from(arr1).concat(Array.from(arr2)); console.log(arr3); // [1, 2, 3, 4, 5, 6]
Array.from()方法還可以傳入一個map函數來對每個元素進行處理。
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let arr3 = Array.from(arr1, x => x * 2).concat(Array.from(arr2, x => x * 2)); console.log(arr3); // [2, 4, 6, 8, 10, 12]
五、使用reduce()方法合併數組
reduce()方法也可以用來合併兩個數組。reduce()方法接受一個回調函數和一個初始值。回調函數用於處理每個數組元素,並將結果累加到初始值中。
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let arr3 = arr1.reduce((prev, curr) => prev.concat([curr]), []).concat(arr2.reduce((prev, curr) => prev.concat([curr]), [])); console.log(arr3); // [1, 2, 3, 4, 5, 6]
上面的代碼等同於下面的代碼:
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let arr3 = arr1.reduce((prev, curr) => [...prev, curr], []).concat(arr2.reduce((prev, curr) => [...prev, curr], [])); console.log(arr3); // [1, 2, 3, 4, 5, 6]
六、小結
JavaScript提供了多種方法來合併數組,我們需要根據實際情況選擇最合適的方法。
- 如果在一個數組末尾添加一個數組,則使用concat()方法或spread operator(…)操作符。
- 如果需要將一個數組中的元素插入到另一個數組的中間位置,則使用spread operator(…)操作符。
- 如果需要在舊版本的JavaScript中合併數組,則可以使用push()方法和apply()方法。
- 如果需要對數組中的元素進行處理,則可以使用Array.from()方法或reduce()方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/244566.html