数组的创建
第一种:
代码如下:
var colors = new Array();
var colors = new Array(20);//创建包含20项的数组
var colors = new Array("Greg");//创建包含1项,即字符串"Greg"的数组
var colors = new Array("red","blue","green"); //创建包含3项
第二种:
代码如下:
var colors = ["red","blue","green"];
var colors = [];//创建一个空数组
注意:数组的索引是从0开始的
1. length属性
length属性中保存数组的项数,如:
代码如下:
var colors = ["red","blue","green"];
alert(colors.length); //3
length属性不是只读的,可以利用length属性在数组的末尾移除项,或者添加新的项,如:
代码如下:
var colors = ["red","blue","green"];
colors.length = 2;
alert(colors); //red,blue
colors[colors.length] = "black";
alert(colors); //red,blue,black
2.join()方法,连接数组中的项
代码如下:
var colors = ["red","blue","green"];
alert(colors.join(",")); //red,blue,green
alert(colors.join("||")); //red||blue||green
3.数组的栈方法:push()和pop()
push()方法 可以接受任意数量的参数把它们逐个添加的数组的末尾,并返回修改后数组的长度
pop()方法 从数组末尾移除最后一项,减少数组的length值,返回移除的项
代码如下:
var colors = new Arrary(); //创建一个数组
var count = colors.push("red","green"); //推入两项到数组末尾
alert(count); //2
count = colors.push("black"); //推入一项到数组末尾
alert(count); //3
var item = colors.pop(); //移除最后一项并返回该值
alert(item); //"black"
alert(count); //2
4.数组的队列方法:push()和shift()、unshift()
push()方法同上
shift()方法 移除数组中的第一项并返回该项,数组长度减1
unshift()方法 在数组前端添加任意项,并返回新数组的长度
代码如下:
var colors = new Arrary(); //创建一个数组
var count = colors.push("red","green"); //推入两项到数组末尾
alert(count); //2
count = colors.push("black"); //推入一项到数组末尾
alert(count); //3
var item = colors.shift(); //移除第一项并返回该值
alert(item); //"red"
alert(colors); //green,black
count = colors.unshift("blue"); //推入一项到数组前端
alert(count); //3
alert(colors); //blue,green,black
5.重排序方法:reverse()和sort()
reverse()方法 反转数组项的顺序
sort()方法 默认按字符串大小升序排列数组项,可以接受一个比较大小的函数作为参数
代码如下:
var values = [1,2,3,4,5];
values.reverse();
alert(values); //5,4,3,2,1
代码如下:
//升序排序函数
function compare(value1,value2) {
if (value1 < value2) {
return -1; //降序改为1
} else if (value1 > value2) {
return 1; //降序改为-1
} else {