1.数组
1.1.数组元素的读写
> var a=["world"]
undefined
> value=a[0]
'world'
> a[1]=3.14
3.14
> i=2
2
> a
[ 'world', 3.14 ]
> a[i]=3
3
> a[i+1]="hello"
'hello'
> a
[ 'world',
3.14,
3,
'hello' ]
> a[a[i]]=a[0]
'world'
> a
[ 'world',
3.14,
3,
'world' ]
> a.length
4
1.2.稀疏数组
在一个数组中有undefined这样的元素,就称为稀疏数组
> var a1 = [,,,]; // This array is [undefined, undefined, undefined]
undefined
> var a2 = new Array(3); // This array has no values at all
undefined
> 0 in a1 // => true: a1 has an element with index 0 这里和书本里面预期不一致。nodejs里面的实现可能不一样吧。
false
> 0 in a2 // => false: a2 has no element with index 0
false
> a1
[ , , ]
> a2
[ , , ]
> a1[0]
undefined
> a2[0]
undefined
> var b1=[,]
undefined
> var b2=[undefined]
undefined
> 0 in b1
false
> 0 in b2
true
>
1.3.数组元素的添加和删除
push()
pop()
unshift()
shift()
splice()是个通用的方法用来插入、删除或替换数组元素。
1.4.数组遍历
for/in循环
for循环
如果算法依赖于遍历的次序,最好不要使用for/in循环而用常规的for循环或者forEach()方法
var data = [1,2,3,4,5]; // This is the array we want to iterate
var sumOfSquares = 0; // We want to compute the sum of the squares of data
data.forEach(function(x) { // Pass each element of data to this function
sumOfSquares += x*x; // add up the squares
});
sumOfSquares // =>55 : 1+4+9+16+25
稀疏数组的遍历
for(var index in sparseArray) {
var value = sparseArray[index];
// Now do something with index and value
}
或者更进一步过滤掉不想要的属性
for(var i in a) {
if (!a.hasOwnProperty(i)) continue; // Skip inherited properties
// loop body here
}
1.5.数组方法
1.5.1.ECMASCRIPT3中的数组方法
join
reverse
sort
concat
slice
splice
push
pop
unshift
shift
toString
toLocaleString
1.5.2.ECMASCRIPT5中的数组方法
forEach
map
filter
every
some
reduce
reduceRight
indexOf
lastIndexOf
1.6.数组类型
Array.isArray()
instanceof操作符,尽量不要使用这个操作符,不能被视为一个可靠地数组检测方法。因为instanceof的意思就是作为一个类构造函数的实例,在多窗口或窗体(frame)的web浏览器中,会存在多个类构造函数,就会发生混淆。
下面是一个兼容ECMASCRIPT3和ECMASCRIPT5的做法
var isArray = Function.isArray || function(o) {
return typeof o === "object" &&
Object.prototype.toString.call(o) === "[object Array]";
};