JavaScript Array

    数组基础:创建数组,访问数组,遍历数组

创建数组:

// Create an empty array
var emptyArray = [ ];

// Create an array of fruit
var fruits = [ "apple", "pear", "orange", "banana" ];

访问数组:

arrayName[index]

 遍历数组: 

var fruits = new Array ( "apple", "pear", "orange", "banana", "peach", "strawberry" );

for ( i=0; i < fruits.length; i++ )
{
alert ( fruits[i] );
}

 

   数组中级:截取数组,连接数组,数组的转换,增加和删除数组中的值,数组排序

slice()方法:   数组高级:数组的嵌套,遍历嵌套数组。

arraySlice = array.slice ( begin [, end] )

concat()方法:  

result = array.concat ( value1, value2, ..., valueN );

toString() 和 join()方法: 

 

result = array.toString ( );
result
= array.join ( separator );

unshift(), shift(), push(), pop() and splice() 

 

Adding and removing in the middle of an array: splice()   

 

removedElements = array.splice ( index, numberToRemove, [value1][, value2, ..., valueN] );

 

Summarizing unshift(), shift(), push() and pop()

unshift()
Adds elements to the start of an array
shift()
Removes 1 element from the start of an array
push()
Adds elements to the end of an array
pop()
Removes 1 element from the end of an array

   数组高级:嵌套数组,数组遍历

Nested Arrays

var pets = new Array ( );
pets[
0] = new Array ( "Sheba", 13, "cat" );
pets[
1] = new Array ( "Jasper", 12, "dog" );
alert ( pets[
0][0] + " is a " + pets[0][1] + " year old " + pets[0][2] ); // Displays "Sheba is a 13 year old cat"
alert ( pets[1][0] + " is a " + pets[1][1] + " year old " + pets[1][2] ); // Displays "Jasper is a 12 year old dog"

Looping nested Array

 

代码
var pets = new Array ( );
pets[
0] = new Array ( "Sheba", 13, "cat" );
pets[
1] = new Array ( "Jasper", 12, "dog" );
var dinosaurs = new Array ( );
dinosaurs[
0] = new Array ( "Cyril", 45, "Tyrannosaur" );
dinosaurs[
1] = new Array ( "Gertrude", 72, "Brontosaur" );
var animals = new Array ( pets, dinosaurs );
alert ( animals[
0][1][0] + " is a " + animals[0][1][1] + " year old " + animals[0][1][2] ); // Displays "Jasper is a 12 year old dog"

for ( i=0; i<animals.length; i++ )
{
for ( j=0; j<animals[i].length; j++ )
{
alert ( animals[i][j][
0] + " is a " + animals[i][j][1] + " year old " + animals[i][j][2] );
}
}

 

posted @ 2010-10-30 10:00  e.e.p  阅读(400)  评论(0编辑  收藏  举报