数组(Arrays)

JavaScript数组实际上是对象。

数组字面符

1
2
3
4
5
6
7
8
9
var empty = [];
var numbers = [
	'zero', 'one', 'two', 'three', 'four',
	'five', 'six', 'seven', 'eight', 'nine'
];
empty[1]     // undefined
numbers[1]   // 'one'
empty.length   // 0 
numbers.length // 10

Length

JavaScript数组的length不是容量的上限,length属性的值是这个数组的最大属性名加1。

1
2
3
4
var myArray = []; 
myArray.length // 0
myArray[1000000] = true;
myArray.length // 1000001

length可以被显式的设置,设置比length更大的值不会给数组分配更多的空间,设置比length小的值则会删除下表大于等于新length的属性。

1
2
3
4
5
6
7
8
numbers.length = 3;
// numbers is ['zero', 'one', 'two']

numbers[numbers.length] = 'shi';
// numbers is ['zero', 'one', 'two', 'shi']

numbers.push('go');
// numbers is ['zero', 'one', 'two', 'shi', 'go']

Delete

delete操作会从数组中删除元素。(只会删除值,但原有的名称/属性会被保留)。

1
2
delete numbers[2];
// numbers is ['zero', 'one', undefined, 'shi', 'go']

如果要真正删除一个元素可以使用splice方法

1
2
numbers.splice(2, 1);
// numbers is ['zero', 'one', 'shi', 'go']

Enumeration

for in 语句可以用于迭代数组的所有属性,但是不能保证自然数字顺序。更好的选择是使用普通for循环,。

1
2
3
4
var i;
for (i = 0; i < myArray.length; i += 1) {
	document.writeln(myArray[i]); 
}

关于使用数组和对象的困惑

当属性名称是小的一系列的数字时使用数组,否则使用对象。

数组判断

1
2
3
var is_array = function (value) {
	return Object.prototype.toString.apply(value) === '[object Array]';
};

方法(methods)

可以通过Array.prototype扩充数组方法。

1
2
3
4
5
6
7
Array.method('reduce', function (f, value) { 
	var i;
	for (i = 0; i < this.length; i += 1) { 
		value = f(this[i], value);
	}
  return value;
});
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// Create an array of numbers.
var data = [4, 8, 15, 16, 23, 42];
// Define two simple functions. One will add two 
// numbers. The other will multiply two numbers.
var add = function (a, b) { 
	return a + b;
};
var mult = function (a, b) { 
	return a * b;
};
// Invoke the data's reduce method, passing in the
// add function.
var sum = data.reduce(add, 0); // sum is 108
// Invoke the reduce method again, this time passing 
// in the multiply function.
var product = data.reduce(mult, 1); // product is 7418880

可以直接给数组添加属性,但是length长度不会增加

1
2
3
4
5
// Give the data array a total function.
data.total = function () { 
	return this.reduce(add, 0);
};
total = data.total(); // total is 108

范围(Dimensions)

数组默认不会初始化,如果访问不存在的元素会返回undefined

一维数组初始化方法

1
2
3
4
5
6
7
8
9
Array.dim = function (dimension, initial) { 
	var a = [], i;
	for (i = 0; i < dimension; i += 1) { 
		a[i] = initial;
	}
	return a; 
};
// Make an array containing 10 zeros. 
var myArray = Array.dim(10, 0);

二维数组初始化

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Array.matrix = function (m, n, initial) { 
	var a, i, j, mat = [];
	for (i = 0; i < m; i += 1) {
		a = [];
		for (j = 0; j < n; j += 1) {
			a[j] = initial; 
		}
		mat[i] = a;
	}
  return mat;
};
// Make a 4 * 4 matrix filled with zeros. 
var myMatrix = Array.matrix(4, 4, 0);