concat( )方法:使用concat()方法可以将两个或多个数组合并成一个数组。
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const mergedArr = arr1.concat(arr2)
console.log(mergedArr)
. . .(展开操作符):使用展开操作符可以将一个数组中的所有元素解开,并将它们放入另一个数组中。(不会扁平化数组)
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const mergedArr = [...arr1, ...arr2]
console.log(mergedArr)
push()+ apply():使用push()方法将一个数组中的所有元素添加到另一个数组的末尾,并在apply()方法中使用第二个数组作为参数。
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
Array.prototype.push.apply(arr1, arr2)
console.log(arr1)
reduce()方法:使用reduce()方法遍历一个数组,并将其中的每个元素添加到另一个数组中
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const mergedArr = arr2.reduce((acc, cur) => {
acc.push(cur)
return acc
}, arr1)
console.log(mergedArr)
splice()方法:使用splice()方法可以将一个数组中的元素插入到另一个数组的指定位置
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
arr1.splice(2, 0, ...arr2)
console.log(arr1)
ES6 Array.from()方法:使用Array.from()方法可以将类似数组的对象或可迭代对象转换为数组,并将其与另一个数组合并
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const mergedArr = Array.from([...arr1, ...arr2])
console.log(mergedArr)
ES6 Array.of()方法:使用Array.of()方法可以将一组值转换为数组,并与另一个数组合并
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const mergedArr = Array.of(...arr1, ...arr2)
console.log(mergedArr)
ES6 Array.prototype.flat()方法:使用flat()方法可以将一个嵌套数组展开,并与另一个数组合并。(数组扁平化)
const arr1 = [1, 2, [3, 4]]
const arr2 = [5, 6]
const mergedArr = arr1.flat().concat(arr2)
console.log(mergedArr)