- 問答:數組方法里
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`
 值得注意的是:參數須是原字符串中所擁有的,否則如同省略參數;
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"]```