push与concat

push

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

语法:

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

 

concat

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

语法:

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

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

 

//push
var sports = ['soccer', 'baseball'];
var total = sports.push('football', 'swimming');

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

 

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

//push
var 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
//concat
var 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]

转载于:https://www.cnblogs.com/huanghongxia/p/4045843.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值