合并js数组有以下两种常用方法:
vara=[ 1,2,3 ],b=[ 4,5,6 ];
1.a.concat(b ); 得到//1、2、3、4、5、6;
1.1该数组之前合并后,该数组的元素在前面
1.2可以利用它复制数组。 a.concat(a );
1.3数组的长度没有限制。 返回值是组合的数组
1.4千万级序列加起来约30毫秒
2.array.prototype.push.apply(a,b ) or a.push.apply(a ) a,b );
2.1.array.prototype.push.apply (a,b ); //a,b的2个排列都是合并后的排列
2.2数组长度有限制,因浏览器而异,一般不能超过10万
2.3返回值是合并后数组的长度
2.4万数据左右的性能与concat基本相同,约2毫秒
总结:测试结果表明,还是使用concat稍微划算一点。 如您所见,如果更改两个数组,apply方法的性能自然会变慢。 另外,也有极限。 在这里再拉一个,很多人也不知道什么时候用
json什么时候使用数组? 频繁添加、删除时尽量使用json。 这是数组的缺点,所以频繁获取数据时使用数组。 因为时间有限,所以下次专门来提这个话题。
请共享测试concat (和Array.prototype.push.apply(a )的代码,根据需要取下来玩
函数测试类
var testArray1=[];
var testArray2=[];
this.resetArray=function () {
for(varI=0; i10000000; I ) {
Testarray1.push(I;
Testarray2.push(I1000000;
}
}
this.applyTest=function (
var startTime=0,
结束时间=0;
console.log ('合并开始于' (startTime=new Date ) ).getTime ) )
varaa=array.prototype.push.apply (testarray 1,testArray2);
console.log(aa;
console.log ('合并完成的时间为' (endTime=new Date ) ).getTime );
console.log ('数组合并所需的时间为'() )结束时间-开始时间);
}
this.concatTest=function (
var startTime=0,
结束时间=0;
console.log ('合并开始于' (startTime=new Date ) ).getTime ) )
varaa=testarray1. concat (testarray2);
console.log(aa.length );
console.log ('合并完成的时间为' (endTime=new Date ) ).getTime );
console.log ('数组合并所需的时间为'() )结束时间-开始时间);
}
}
var apply=new testClass (;
apply.resetArray (;
apply.applyTest (;
var concat=new testClass (;
concat.resetArray (;
concat.concatTest (;
这是CSDN博客《蝾螈筑巢》的原创文章,符合CC 4.0 BY-SA版权协议。 请附上原文出处的链接和本声明。
原文链接: https://blog.csdn.net/迷你路灯/article/details/51433551