- 问答:数组方法里
push
,pop
,shift
,unshift
,split
,join
分别是什么作用。
-
push
可以在数组的最后一个元素后插入任意数量新的元素,返回原数组改动后的length属性的值;
var a=[1,2,3,4,5,6],b=[1,2,3,4,5,6,7];
console.log(a.push(0)); //返回7
console.log(b.push(0,9)); //返回9
console.log(a); //返回[1,2,3,4,5,6,0]```
- `pop`是将数组的最后一个元素删除,并返回删除的元素,对于空数组,返回undefined;
var a=[1,2,3,4,5,6];
console.log(a.pop()); //返回6
console.log(a); //返回[1,2,3,4,5]```
-
shift
将数组的第一个元素删除,并返回删除的元素undefined,对于空数组,返回undefined;
var a=[1,2,3,4,5,6];
console.log(a.shift()); //返回1
console.log(a); //返回[2,3,4,5,6]```
- `unshift`在数组的最前插入任意数量新的元素,返回数组改动后的length属性的值;
var a=[1,2,3,4,5,6];
console.log(a.unshift(9)); //返回7
console.log(a); //返回[9,1,2,3,4,5,6]```
-
join
可以使用参数把数组元素连接为一个字符串并返回(如果省略参数arr.join()
,则用,
连接),返回的字符串不包括参数本身,原数组不改变;
var a=[1,2,3,4,5,6];
console.log(a.join('')); //返回123456
console.log(a.join('-')); //返回 1-2-3-4-5-6
console.log(a.join()); //返回 1,2,3,4,5,6
console.log(a);//返回 [1,2,3,4,5,6]```
- `split`
![split.PNG](http://upload-images.jianshu.io/upload_images/2150964-f1d83a8561250093.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 值得注意的是:参数须是原字符串中所拥有的,否则如同省略参数;
var b="natural is the way";
console.log(b.split()); //返回 ["Natural is the way"]
console.log(b.split('+')); //返回 ["Natural is the way"]
console.log(b.split(' '));//返回 ["natural", "is", "the", "way"]
console.log(b.split(' ',1)); //返回 ["natural"]
console.log(b.split(' ',2)); //返回 ["natural", "is"]```