1.concat
var arr1=[1,2,3];
var arr2=['a','b'];
var arr3=[null,undefined];
var arr = arr1.concat(arr2,arr3); //合并一
var arr4=[['c','d'],3];
arr=arr1.concat(arr4)
//concat函数,可以合并多个数组,不影响原数组,但会造成内存浪费,不能处理嵌套数组
2.for+push or unshift
function marry_for(arr1,arr2) {
if(arr1.length > arr2.length){
for(var i=0;i<arr2.length;i++){
arr1.push(arr2[i]);
}
return arr1;
}else{
for(var i=0;i<arr1.length;i++){
arr2.push(arr1[i]);
}
return arr2;
}
}
arr1 = [1,2,3,4] ;arr2 = [5,[6,7,8],9,10] ;
console.log(marry_for(arr1, arr2));
3.for+foreach+push
function marry_foreach(arr1,arr2) {
if(arr1.length > arr2.length){
arr2.forEach(function (value,index,arr2) {
arr1.push(value);
})
return arr1;
}
else{
arr1.forEach(function (value,index,arr1) {
arr2.push(value);
})
return arr2;
}
}
arr1 = [1,2,3,4] ;arr2 = [5,[6,7,8],9,10];
console.log(marry_foreach(arr1,arr2));
4.reduce+reduceRight
function marry_reduce(arr1,arr2) {
if(arr1.length>arr2.length){
return arr2.reduce(function (prev, second) { //升序添加
prev.push(second);
return prev;
},arr1)
}
else{
return arr1.reduceRight(function (prev,second) { //降序添加
prev.push(second);
return prev;
},arr2)
}
}
arr1 = [1,2,3,4] ;arr2 = [5,[6,7,8],9,10] ;
console.log(marry_reduce(arr1,arr2)
5.apply
function marry_apply(arr1,arr2){
return Array.prototype.concat.apply([],arguments)
}
arr1 = [1,2,3,4] ;arr2 = [5,[6,7,8],9,10] ;
console.log(marry_apply(arr1,arr2))
参考引用:https://blog.csdn.net/Cinderella_hou/article/details/52303570