首页 > 代码库 > push与concat

push与concat

push

push()方法将一个或多个元素添加到数组的末尾,并且返回新的数组长度。

语法:

arr.push(element1, ..., elementN)

 

concat

concat() 方法用于连接两个或多个数组。该方法不会改变现有的数组,而仅仅会返回被连接数组的一个副本。

语法:

var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])

因此,push与concat的对原数组的操作是不同的,push是在原数组基础上操作的,而concat的原数组不会改变。

 

//pushvar sports = [‘soccer‘, ‘baseball‘];var total = sports.push(‘football‘, ‘swimming‘);console.log(sports); // [‘soccer‘, ‘baseball‘, ‘football‘, ‘swimming‘]console.log(total);  // 4
//concatvar sports = [‘soccer‘, ‘baseball‘];var total = sports.concat(‘football‘, ‘swimming‘);console.log(sports); // [‘soccer‘, ‘baseball‘]console.log(total);  // [‘soccer‘, ‘baseball‘,‘football‘, ‘swimming‘]

 

添加长度大于1的数组,push会将数组作为整体添加到数组末尾,而concat则不会

//pushvar sports = [‘soccer‘, ‘baseball‘];var total = sports.push([‘football‘, ‘swimming‘]);console.log(sports); //["soccer", "baseball", Array[2]]0: "soccer"1: "baseball"2: Array[2]length: 3__proto__: Array[0]console.log(total);  // 3
//concatvar sports = [‘soccer‘, ‘baseball‘];var total = sports.concat([‘football‘, ‘swimming‘]);console.log(sports); // ["soccer", "baseball"]console.log(total);  // ["soccer", "baseball", "football", "swimming"] 

 

那么在上一步的操作中如何使用push方法,使sports变成["soccer", "baseball", "football", "swimming"] ,而不是["soccer", "baseball", Array[2]]?[1]

首先push和concat均可使用call()和Apply(), 其中

apply()方法能劫持另外一个对象的方法,继承另外一个对象的属性.

Function.apply(obj,args)方法能接收两个参数
obj:这个对象将代替Function类里this对象
args:这个是数组,它将作为参数传给Function(args-->arguments)

 call()和apply的意思一样,只不过是参数列表不一样.

Function.call(obj,[param1[,param2[,…[,paramN]]]])
obj:这个对象将代替Function类里this对象
params:这个是一个参数列表

从Apply()的定义上,你大概已经知道解决方法了,利用Apply,将数组作为参数传给push,这样就能得到你想要的结果了。

var sports = [‘soccer‘, ‘baseball‘];var total = Array.prototype.push.apply(sports,[‘football‘, ‘swimming‘]);
/*or var total = sports.push.apply(sports,[‘football‘, ‘swimming‘]);
*/

console.log(sports);
// ["soccer", "baseball", "football", "swimming"]
console.log(total); // 4

 

相关链接:

[1] stackoverflow  How to extend an existing JavaScript array with another array? [duplicate]

push与concat