數(shù)組的方法有許多个扰,但來來回回常用的也就那幾種,特此記錄葱色,以備遺忘之需递宅。
將數(shù)組合并成字符串
- toString()
直接把數(shù)組里的內(nèi)容變成一個字符串
var arr = [12,25,30,92]; var arr1 = arr.toString(); //arr1 = 12,25,30,92
- join()
以某種符號將數(shù)組內(nèi)容串聯(lián)成一個字符串
var arr = [12,25,30,92]; var arr1 = arr.join('*'); //arr1 = 12*25*30*92
增加數(shù)組內(nèi)容
1.push()
添加的內(nèi)容按順序放在數(shù)組最后面,并自動加長度
var arr = [12,25,30,92];
var arr1 = arr.push(51苍狰,65); //arr1 = [12,25,30,92,51,65]
2.unshift()
添加的內(nèi)容按順序放在數(shù)組的最前面办龄,并自動增加長度
var arr = [12,25,30,92];
var arr1 = arr.unshift(51,65); //arr1 = [51,65,12,25,30,92]
取出數(shù)組內(nèi)容
1.pop()
取出數(shù)組最后一個元素淋昭,并返回該值且在數(shù)組中消失
var arr = [12,25,30,92];
var poped = arr.pop();
//arr = [12,25,30] poped = 92
2.shift()
取出數(shù)組第一個元素俐填,并返回該值且在數(shù)組中消失
var arr = [12,25,30,92];
var shifted = arr.shift();
//arr = [25,30,92] shifted = 12
3.slice(begin,end)
淺復(fù)制了數(shù)組內(nèi)容,begin為開始復(fù)制的位置,end為結(jié)束復(fù)制的位置
var arr = [12,25,30,92];
var arr1 = arr.slice(1,3);
//arr1 = [25,30,92]
排序
排序的方法倒是只有一種翔忽,即sort()英融,但是分為升序和降序
1.升序
默認(rèn)為升序
var arr = [12,0,25,30,92];
var arr1 = arr.sort();
//arr1 = [0,12,25,30,92]
還有另一種寫法記得ab不能寫反
var arr = [12,0,25,30,92];
var arr1 = arr.sort(functiion(a,b){
return a-b;
});
//arr1 = [0,12,25,30,92]
2.降序
var arr = [12,0,25,30,92];
var arr1 = arr.sort(functiion(a,b){
return b-a;
});
//arr1 = [92,30,25,12,0]
替換數(shù)組內(nèi)容
splice(start,items,inplace);此方法從數(shù)組的start位置開始刪除items個元素,并添加inplace元素
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
// removes 0 elements from index 2, and inserts 'drum'
var removed = myFish.splice(2, 0, 'drum');
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removed is [], no elements removed
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removes 1 element from index 3
removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']
// removes 1 element from index 2, and inserts 'trumpet'
removed = myFish.splice(2, 1, 'trumpet');
// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
// removed is ['drum']
// removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue'
removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
// removed is ['angel', 'clown']
// removes 2 elements from index 2
removed = myFish.splice(myFish.length -3, 2);
// myFish is ['parrot', 'anemone', 'surgeon']
// removed is ['blue', 'trumpet']
這一個引用了devdocs的demo
合并數(shù)組
concat();將兩個數(shù)組合并成一個新數(shù)組歇式,并返回該數(shù)組
var arr1 = [12,23,34];
var arr2 = ['hello','world'];
var arr3 =arr1.concat(arr2);
//arr3 = [12,23,34,'hello','world']
哪個數(shù)組使用了此方法驶悟,哪個就在前