創(chuàng)建數(shù)組:
1. var colors = new Array (); //括號中可以填入項(xiàng)目數(shù)量
2. var colors = new Array ("red","blue","green"); //可以之間填入數(shù)組包含的項(xiàng)
PS:new可以省略,第二種的括號可以改為方括號。
讀取與設(shè)置數(shù)組的值:
用方括號,并填入基于0的數(shù)字
var colors = new Array ["red","blue","green"];
array [1] = "blue" //顯示第二項(xiàng)
array [3] = "black" //增加第四項(xiàng)
數(shù)組的項(xiàng)數(shù)保存在length屬性中:
var colors = new Array ["red","blue","green"]; //創(chuàng)建一個(gè)有三個(gè)字符串的數(shù)組
var name = []; //創(chuàng)建一個(gè)空數(shù)組
alert(colors.length); //3
alert(colors.length); //0
可以設(shè)置length屬性從數(shù)組的末尾移除項(xiàng)
var colors = new Array ["red","blue","green"]; //創(chuàng)建一個(gè)有三個(gè)字符串的數(shù)組
colors.length = 2;
alert(colors[2]); //undefined
colors有3個(gè)值,將length屬性設(shè)置成2會移除最后一項(xiàng),再訪問時(shí)顯示undefined
添加新項(xiàng)
var colors = new Array ["red","blue","green"]; //創(chuàng)建一個(gè)有三個(gè)字符串的數(shù)組
colors.length = 4;
alert(colors[3]); //undefined
將length屬性設(shè)置大于數(shù)組項(xiàng)數(shù),新增的項(xiàng)為undefined
var colors = new Array ["red","blue","green"];
colors[colors.length] = "black"; //在位置3添加黑色
colors[colors.length] = "brown"; //在位置4添加棕色
PS:數(shù)組的最后一項(xiàng)索引為length-1