一:Array 类
var aColor = new Array();
aColor[0]="red";
aColor[1]="green";
aColor[2]="blue";
或
var aColor= new Array(30);
或
var aColor =new Array("red","green","blue");
alert(aColor[1]); //outputs "green"
alert(aColor.length); // 3
添加值
aColor[25]="purple";
alert(aColor.length) //26
alert(aColor[24]); //null
Array对象覆盖了toString()方法和valueOf()方法,返回特殊的字符串.
alert (aColor.toString()); //"red,green,blue"
alert(aColor.valueOf()); //"red,green,blue"
连接字符串Join
alert(aColor.join(",")); //"red,green,blue"
alert(aColor.join("-")); //"red-green-blue"
Array对象具有两个String类具有的方法,即concat()方法和slice()方法
var aColor = ["red","green","blue"];
var aColor2 =aColor.concat("yellow","purple");
alert(aColor2.toString()); //"red,green,blue,yellow,purple"
slice()方法返回的是具有特定项的新数值
var aColor2 =["red","green","blue","yellow","purple"];
var aColor3 =aColor2.slice(1);
var aColor4 =aColor2.slice(1,4);
alert(aColor3.toString()); //"green,blue,yellow,purple"
alert(aColor4.toString()); //"green,blue,yellow"
Array对象的push()和pop()方法
var stack =new Array;
stack.push("red");
stack.push("green");
stack.push("blue");
alert(stack.toString());//"red,green,blue"
var vItem= stack.pop();
alert(vItem); // "blue"
alert(stack.toString()); //"red,green"
Array对象还提供了操作第一项的方法shift()将删除数值的的一个项,将其作为函数值返回。
另一个方法是unshift(),它把一个项放在数组的第一个位置,然后把余下的项向下移动一个位置。
var aColor =["red","green","yellow"];
var vItem = aColor.shift();
alert(aColor.toString()); //"green,yellow"
alert(vItem); //"red"
aColor.unshift("black");
alert(aColor.toString()); //"black,green,yellow"
通过调用shift()和unshift()方法可以是Array对象具有队列的行为--后进后出。
var queue = ["red","green","blue"];
queue.push("black");
alert(queue.toString()); //"red,green,blue,black"
var sNextColor= queue.shift();
alert(sNextColor); //"red"
alert(queue.toString()); //"green,blue,black"
有两种与数组项的顺序有关的方法,reverse(),sort()
var aColor=["red","green","blue"];
aColor.reverse();
alert(aColor.toString()); //"blue,green,red"
sort()方法首先调用toString()方法,将所有的值转换为字符串,然后根据字符代码比较数组项
var aColor=["red","green","blue"];
aColor.sort();
alert(aColor.toString()); // "blue,green,red"
splice()方法 把数据项插入数组的中部---暂时不讨论,该方法的变体有很多用途。