js--引用类型Array--2.数组合并几种方法

js数组也是很重要的一块,所以准备对数组的操作等写一个系列。
1.第一部分是二元数组的基础知识。
http://blog.csdn.net/github_34514750/article/details/51049935
2.本部分讲解数组的几种合并方法优劣比较
3.第三部分讲解数组简单复制和深度复制
http://blog.csdn.net/github_34514750/article/details/56677750

根据第一部分的基础知识,我们最容易想到的是concat、push、unshift

1.concat合并数组

concat是生成一个新数组,内存则是a和b的和

var a = [1,2,3],
    b = ["ab","cd","ef"],
    c = a.concat(b);
console.log(c);

如图:
这里写图片描述

2.push循环合并数组

push是一个数组的内容加入到另一个中

var a = [1,2,3],
    b = ["ab","cd","ef"],
    i,
    len;
for(i = 0,len = b.length;i < len;i++) {
    a.push(b[i]);
}
b = null;//b可以清空

这里写图片描述

3.unshift循环合并数组

若a比较少,则希望a插入到b前边,这样节省时间

var a = [1,2,3],
    b = ["ab","cd","ef"],
    i;
for(i = a.length-1;i >= 0;i--) {
    b.unshift(a[i]);
}
console.log(b);
a = null;//a可以清空

这里写图片描述

4.reduce合并数组
var a = [1,2,3],
    b = ["ab","cd","ef"],
    i;
b.reduce(function(prev,curr){
   prev.push(curr);
   return prev;
},a);
console.log(a); 

这里写图片描述

5.reduceRight合并数组
var a = [1,2,3],
        b = ["ab","cd","ef"],
        i;
    a.reduceRight(function(prev,curr){
        prev.unshift(curr);
        return prev;
    },b);
    console.log(b);

这里写图片描述

6.用Array.prototype.push.apply合并数组
var a = [1,2,3],
    b = ["ab","cd","ef"];
// call和apply可以用来重新定义函数的执行环境,apply中的第一个参数a用于指定将要调用函数push的对象,参数是b
// 其实就是在a的上下文环境中执行Array.prototype.push函数,参数是b
Array.prototype.push.apply(a,b);
console.log(a);

这里写图片描述

7.用Array.prototype.unshift.apply合并数组
var a = [1,2,3],
    b = ["ab","cd","ef"];
// 其实就是在b的上下文环境中执行Array.prototype.unshift函数,参数是a
Array.prototype.unshift.apply(b,a);
console.log(b);

这里写图片描述
问题
1.js引擎都会有拷贝数据长度的限制,若数组很大,肯定会超出push或unshift允许调用堆栈的限制,则可以结合splice使用

function combineInto(a,b) {
     var len = a.length;
     for (var i=0; i < len; i=i+5000) {
         b.unshift.apply( b, a.slice( i, i+5000 ) );
     }
 }
  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值