var arr1 = [1,2,3,-1]
var arr2 = [4,5,6,7,8,9,10,12,13,14,15,16,17,18,29,30,31,32,33,34,35,36,37,38,39,40]
var arr = arr1.concat(arr2)
借用apply方法 ,push、splice也可和来连接数组。因为push没有创建新数组,如果想要保挂原对象的引用,可使用push方法。
var testConcat = function(abc) {
var arr1 = [1,2,3,-1]
var arr2 = [4,5,6,7,8,9,10,12,13,14,15,16,17,18,29,30,31,32,33,34,35,36,37,38,39,40]
var arr = arr1.concat(arr2)
}
var testPush = function(abc) {
var arr1 = [1,2,3,-1]
var arr2 = [4,5,6,7,8,9,10,12,13,14,15,16,17,18,29,30,31,32,33,34,35,36,37,38,39,40]
Array.prototype.push.apply(arr1, arr2)
}
var count = 1000000
var date = Date.now()
for (var i = 0; i < count; i++) {
testConcat()
}
console.log(Date.now() - date)
var date = Date.now()
for (var i = 0; i < count; i++) {
testPush()
}
console.log(Date.now() - date)
结果:
时间:
1470
465
json什么时候用数组,如果频繁添加删除的尽量用json,因为这是数组的短处,如果频繁取数据的用数组。