Array的基本創建以及Array中length屬性特點,具體代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Array類型</title>
<script type="text/javascript">
//創建數組基本方式兩種,第一種使用Array構造函數如:var colors=new Array()或new Array(3)或new Array("red","blue","green");
//第二種方式使用數組字面量表示法:var colors=["red","blue","green"];
function arrayBasic(){
var colors=["red","blue","black"];
alert(colors[0]);
alert("原來的長度:"+colors.length);
colors[100]="white";
alert(colors[100]);//雖然數組的長度就3,但是由於數組的大小是可以動態調整的,所有實際上插n個undefined值
alert("現在的長度:"+colors.length);
}
function arrayLength(){
var output="";
var colors=new Array("red","blue","green");
colors[colors.length]="black";//在位置3添加一種顏色
colors[colors.length]="gray";//在位置4添加一種顏色
for(var i in colors){
output+=colors[i]+" , ";
}
alert(colors.length+"---"+output);
}
//length是可讀可寫的
function arrayLengthSet(){
var colors=["red","blue","black"];
alert(colors.length);
colors.length=1;
alert("length="+colors.length+"--value:"+colors[0]);
}
//數組的valueOf()和toString()返回相同的值
function arrayRead(){
var colors=new Array("red","blue","green");
alert(colors.toString());
alert(colors.valueOf());
alert(colors);
//join()方法可以用不同的分隔符來構建字符串
alert(colors.join("||"));
}
</script>
</head>
<body>
<input type="button" value="Array獲取" οnclick="arrayBasic();"/>
<input type="button" value="Array Length" οnclick="arrayLength();"/>
<input type="button" value="Array Length設置" οnclick="arrayLengthSet();"/>
<input type="button" value="Array轉換方法" οnclick="arrayRead();"/>
</body>
</html>