js合并两个或多个数组的方法

方法一:concat方法(不改变原数组)

var arr = [1,2,3];
var arr1 = [{name: 'me'},{age: 18}]
var arr2 = ['a','b','c'];
var arr3 = arr.concat(arr1,arr2)
console.log(arr3)
// (8) [1, 2, 3, {name: 'me'}, {age: 18}, 'a', 'b', 'c']

方法二:push.apply方法 (改变第一个数组,且只能合并前两个数组)

var arr = [1,2,3];
var arr1 = [{name: 'me'},{age: 18}]
var arr2 = ['a','b','c'];
[].push.apply(arr,arr1,arr2)
console.log(arr) 
// (5) [1, 2, 3, {name: 'me'}, {age: 18}]

方法三:解构

var arr = [1,2,3];
var arr1 = [{name: 'me'},{age: 18}]
var arr2 = ['a','b','c'];
var arr3=[...arr,...arr1,...arr2];
console.log(arr3) 
// (8) [1, 2, 3, {name: 'me'}, {age: 18}, 'a', 'b', 'c']

Published by

风君子

独自遨游何稽首 揭天掀地慰生平