數(shù)組的一些常用方法整理
var arr = ['a', 'b', 'c', '1', '2', '3'];
push
在數(shù)組的末尾增加一個或多個元素啦撮,并返回數(shù)組的新長度`console.log(arr.push('x','x','x'))`// 9`arr.push([2])`// [2] 會被當做一項即:arr[6]是[2]
pop
刪除數(shù)組的最后一個元素,并返回這個元素`console.log(arr.pop());`// 3
unshift
在數(shù)組的開頭添加一個或者朵兒元素与倡,并返回數(shù)組新的length值`console.log(arr.unshift())`
shift
刪除數(shù)組的第一個元素谜叹, 并返回這個元素`console.log(arr.shift());`//a
join
將數(shù)組中的所有元素連接成一個字符串交煞。`console.log(arr.join());`//a, b, c, 1, 2, 3
concat
將傳入的數(shù)組或非數(shù)組值與原數(shù)組合并,組成一個新的數(shù)組并返回`console.log(arr.concat(0,9));` //? ['a','b','c','1','2','3',0,9]`console.log(arr.concat([0,9]));` //? ['a','b','c','1','2','3',0,9]``console.log(arr.concat([[9]]));` //? ['a','b','c','1','2','3',0, [9]]`
sort
對數(shù)組的元素做原地的排序, 并返回這個數(shù)組撤卢。arr = [2,0,1,6];console.log(arr.sort());// [0, 1, 2, 6]arr.sort(function(a, b)){console.log(a +'-'+ b);returna - b环凿;// 從小到大returna + b ;// 從大到小}console.log(arr);
slice
把數(shù)組中一部分的錢復(fù)制存入一個新數(shù)組對象中,并返回這個新的數(shù)組arr = [{a:9}];varret = arr.slice(0,1);console.log(ret);// [{a:9}]ret[0].a =10;console.log(arr[0].a);// 10
splice
用新元素替換舊元素凸丸,以此修改數(shù)組的內(nèi)容參數(shù):? ? 第一個參數(shù): 表示開始位置? ? 第二個參數(shù): 長度? ? 剩余參數(shù): 要添加到數(shù)組中的元素`console.log(arr.splice(3,3));`//['1','2','3']
filter方法
filter是指可以刪除數(shù)組中的某一項元素拷邢。
vararr = [1,2,3,4,5];varnewArr = arr,filter(function(item){if(item ==4) {returnfalse;? ? }else{returntrue;? ? }})console.log(newArr);// 1, 2, 3, 5
reverse 方法
reverse() 是指可以顛倒數(shù)組中元素的順序
var arr =[1, 2, 3, 4, 5];arr.reverse();得到新的數(shù)組就是[5, 4, 3, 2, 1];