DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JavaScript基礎知識 >> js常用數組操作方法簡明總結
js常用數組操作方法簡明總結
編輯:JavaScript基礎知識     
//javascript 中的數組分割
var colors = ["red","green","blue"];
//alert(colors.toString());
alert(colors.join("|")); //返回結果是red|green|blue
var colors = ["red","green","blue",null];
alert(colors.join("|"));//red|green|blue|
//注意當數組裡面有值是null或者是undefined的時候 返回的結果是以空的字符串表示的
-------------------------------------------
//數組刪除和添加
var colors = ["red","green","blue"];
//alert(colors.toString());
colors.push("white","test");//返回的結果是數組的長度
alert(colors.join("|"));//結果是red|green|blue|white|test
//往數組的開頭添加元素
var colors = ["red","green","blue","test"];
var item = colors.unshift("first");//數組的開頭添加一個元素
alert(colors.join("|"));//返回最後的數組


//刪除元素
var colors = ["red","green","blue","test"];
var item = colors.pop();//返回刪除的選項結果test
alert(colors.join("|"));//返回最後的數組結果red|green|blue
//刪除開頭元素
var colors = ["red","green","blue","test"];
var item = colors.shift();//刪除數組的第一個選項
alert(colors.join("|"));//返回最後的數組
-------------------------------------------------
//數組順序事例
//順序顛倒
var colors = ["red","green","blue","test"];
colors.reverse();
alert(colors);//結果是:test,blue,green,red
//數組排序
var values = [0,1,5,10,7];
values.sort(compare);
alert(values);
//document.writeln(values);

}
 function compare(value1,value2){
	if(value1<value2){
		return 1 ;
	}else if(value1>value2){
		return -1 ;
	}else return 0 ;
} 
-----------------------------------------------------
//向數組中添加數組 concat()方法
var colors = ["color","red"];
var colors2 = colors.concat(["ccc","bbbb"],'3333',['vvccxx',['oolll','lll']]);
alert(colors2);//返回結果是:color,red,ccc,bbbb,3333,vvccxx,oolll,lll

//slice()方法復制數組中的元素並不會破壞之前的元素
var colors = ["color","red",'eeee','221111'];
var colors2 = colors.slice(1);//從1開始進行復制
alert(colors2);//結果是:red,eeee,221111

var colors = ["color","red",'eeee','221111'];
var colors2 = colors.slice(1,3);//從1開始進行復制到第3個位置結束
alert(colors2);//結果是red,eeee
---------------------------------------------------------------------
//數組中刪除元素
var a = [1,2,3,5,8];
var r = a.splice(0,2); //刪除前2項
alert(a);//結果是3,5,8

var a = [1,2,3,5,8];
var r = a.splice(1,1,100,200); //從第2個數開始刪除一項 然後插入100 200
alert(a);//結果是1,100,200,3,5,8

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved