JS數組方法匯總
shift:刪除原數組第一項,並返回刪除元素的值;如果數組為空白則返回undefined
var a = [1,2,3,4,5];
var b = a.shift(); //a:[2,3,4,5] b:1
unshift:將參數添加到原數組開頭,並返回數組的長度
var a = [1,2,3,4,5];
var b = a.unshift(-2,-1); //a:[-2,-1,1,2,3,4,5] b:7
註:在IE6.0下測試傳回值總為undefined,FF2.0下測試傳回值為7,所以這個方法的傳回值不可靠,需要用傳回值時可用splice代替本方法來使用。
pop:刪除原數組最後一項,並返回刪除元素的值;如果數組為空白則返回undefined
var a = [1,2,3,4,5];
var b = a.pop(); //a:[1,2,3,4] b:5
push:將參數添加到原數組末尾,並返回數組的長度
var a = [1,2,3,4,5];
var b = a.push(6,7); //a:[1,2,3,4,5,6,7] b:7
concat:返回一個新數組,是將參數添加到原數組中構成的
var a = [1,2,3,4,5];
var b = a.concat(6,7); //a:[1,2,3,4,5] b:[1,2,3,4,5,6,7]
splice(start,deleteCount,val1,val2,...):從start位置開始刪除deleteCount項,並從該位置起插入val1,val2,...
var a = [1,2,3,4,5];
var b = a.splice(2,2,7,8,9); //a:[1,2,7,8,9,5] b:[3,4]
var b = a.splice(0,1); //同shift
a.splice(0,0,-2,-1); var b = a.length; //同unshift
var b = a.splice(a.length-1,1); //同pop
a.splice(a.length,0,6,7); var b = a.length; //同push
reverse:將數組反序
var a = [1,2,3,4,5];
var b = a.reverse(); //a:[5,4,3,2,1] b:[5,4,3,2,1]
sort(orderfunction):按指定的參數對數組進行排序
var a = [1,2,3,4,5];
var b = a.sort(); //a:[1,2,3,4,5] b:[1,2,3,4,5]
slice(start,end):返回從原數組中指定開始下標到結束下標之間的項組成的新數組
var a = [1,2,3,4,5];
var b = a.slice(2,5); //a:[1,2,3,4,5] b:[3,4,5]
join(separator):將數組的元素組起一個字串,以separator為分隔字元,省略的話則用預設用逗號為分隔字元
var a = [1,2,3,4,5];
var b = a.join("|"); //a:[1,2,3,4,5] b:"1|2|3|4|5"