當前位置:才華齋>設計>網頁設計>

JavaScript高階程式設計:本地物件Array

網頁設計 閱讀(2.37W)

建立Array物件

JavaScript高階程式設計:本地物件Array

複製程式碼 程式碼如下:

//one

var aValues=new Array();

//two

var aValues=new Array(20);

//three

var aColors=new Array();

aColors[0]="red";

aColors[1]="green";

aColors[2]="blue";

//four

var aColors=new Array("red","green","blue");

//five

var aColors=["red","green","blue"];

join && split

join:連線字串

複製程式碼 程式碼如下:

var aColors=["red","green","blue"];

alert((","));//outputs "red,green,blue"

alert(("-spring-"));//outputs "red-spring-green-spring-blue"

alert(("]["));//outputs "red][green][blue"

split:分拆字串

複製程式碼 程式碼如下:

var sColors="red,green,blue";

var aColors=t(",");//outputs ["red", "green", "blue"]

var redColors=aColors[0]t("");//outputs ["r", "e", "d"]

concat && slice

concat:追加陣列

複製程式碼 程式碼如下:

var aColors=["red","green","blue"];

var aColors2=at("yellow","purple");

alert(aColors);//outputs ["red", "green", "blue"]

alert(aColors2);//outputs ["red", "green", "blue", "yellow", "purple"]

slice:返回具有特定項的新陣列

複製程式碼 程式碼如下:

var aColors=["red","green","blue","yellow","purple"];

var aColors2=e(1);//outputs ["green","blue","yellow","purple"]

var aColors3=e(1,4);//outputs ["green","blue","yellow"]

push && pop

跟棧一樣,Array提供了push和pop方法,push方法用於在Array結尾新增一個或多個項,pop用於刪除最後一個數組項,返回它作為函式值

複製程式碼 程式碼如下:

var stack=new Array;

("red");

("green");

("blue");

alert(stack);//outputs ["red","green","blue"]

var vItem=();

alert(vItem);//outputs ["blue"]

alert(stack);//otputs ["red","green"]

shift && unshift

shift:刪除陣列中第一項,將其作為函式返回值,unshift:把一個項放在陣列的第一個位置,然後把餘下的項向下移動一個位置

複製程式碼 程式碼如下:

var aColors=["red","green","blue"];

var vItem=t();

alert(aColors);//outputs ["green","blue"]

alert(vItem);//outputs ["red"]

ift("black");

alert(aColors);//outputs ["black","green","blue"]

reverse && sort

reverse:顛倒陣列項的順序,sort:按陣列項的值升序排列(首先要呼叫toString()方法,將所有值轉換成字串)

複製程式碼 程式碼如下:

var aColors=["blue","green","red"];

rse();

alert(aColors);//outputs ["red","green","blue"]

();

alert(aColors);//outputs ["blue","green","red"]

注意:

複製程式碼 程式碼如下:

var aColors=[3,32,2,5];

();

alert(aColors);//outputs [2,3,32,5]

這是因為數字被轉換成字串,然後按字元程式碼進行比較的。

splice

splice:把資料項插入陣列的中部

1、用作刪除:只要宣告兩個引數,第一個引數為要刪除的第一個項的`位置,第二個引數為刪除項的個數

複製程式碼 程式碼如下:

var aColors=["red","green","blue","yellow"];

ce(0,2);

alert(aColors);//outputs ["blue", "yellow"]

2、用作插入:宣告三個或以上引數(第二個引數為0)就可以把資料插入指定位置,第一個引數為地始位置,第二個引數為0,第三個及以上引數為插入項

複製程式碼 程式碼如下:

var aColors=["red","green","blue","yellow"];

ce(2,0,"black","white");

alert(aColors);//outputs ["red","green","black","white","blue", "yellow"]

3、用作刪除並插入:宣告三個或以上引數(第二個引數為不0)就可以把資料插入指定位置,第一個引數為地始位置,第二個引數為要刪除的項的個數,第三個及以上引數為插入項

複製程式碼 程式碼如下:

var aColors=["red","green","blue","yellow"];

ce(2,1,"black","white");

alert(aColors);//outputs ["red","green","black","white", "yellow"]