数组是从零开始索引,有序的值列表。他们是一个方便的方式来存储一组同类型的相关项目(例如字符串),但在实际中,一个数组可以包含多种类型的项目,包括其他数组。对象构造和字面声明都可以创建一个数组,在声明后可以给改数组赋一个值列表。
// A simple array with constructor.
var myArray1 = new Array( "hello", "world" );
// Literal declaration, the preferred way.
var myArray2 = [ "hello", "world" ];
字面声明构建数组是首选。参见google 代码指南获取更多信息。
如果数组中的值未知,可以声明一个空数组,通过方法和索引访问都可以添加元素。
// Creating empty arrays and adding values
var myArray = [];
// adds "hello" on index 0
myArray.push( "hello" );
// adds "world" on index 1
myArray.push( "world" );
// adds "!" on index 2
myArray[ 2 ] = "!";
.push是一个把元素添加到数组末尾并使数组得到扩张。你也可以直接用索引添加元素。丢失的索引将用undefined填充。
// Leaving indices
var myArray = [];
myArray[ 0 ] = "hello";
myArray[ 1 ] = "world";
myArray[ 3 ] = "!";
console.log( myArray ); // [ "hello", "world", undefined, "!" ];
如果数组的大小未知,.push更安全。你可以使用索引访问元素以及给元素赋值。
// Accessing array items by index
var myArray = [ "hello", "world", "!" ];
console.log( myArray[2] ); // "!"
数组的方法和属性
.length
.length属性用来获取数组的项目个数。
用.length属性来遍历数组:
// Length of an array
var myArray = [ "hello", "world", "!" ];
console.log( myArray.length ); // 3
用.length属性来遍历数组:
// For loops and arrays - a classic
var myArray = [ "hello", "world", "!" ];
for ( var i = 0; i < myArray.length; i = i + 1 ) {
console.log( myArray[i] );
}
除了使用for/in循环:
// For loops and arrays - alternate method
var myArray = [ "hello", "world", "!" ];
for ( var i in myArray ) {
console.log( myArray[ i ] );
}
.concat
用.concat来连接两个数组
// Concatenating Arrays
var myArray = [ 2, 3, 4 ];
var myOtherArray = [ 5, 6, 7 ];
// [ 2, 3, 4, 5, 6, 7 ]
var wholeArray = myArray.concat( myOtherArray );
使用分隔符字符串加入所有元素,.concat创建一个数组的字符串表示。如果没有分隔符(如无参数调用.join()),数组使用逗号连接:
// Joining elements
var myArray = [ "hello", "world", "!" ];
// The default separator is a comma
console.log( myArray.join() ); // "hello,world,!"
// Any string can be used as separator...
console.log( myArray.join(" ") ); // "hello world !";
console.log( myArray.join("!!") ); // "hello!!world!!!";
// ...including an empty one
console.log( myArray.join("") ); // "helloworld!"