数组类型判断
在ECMAScript5中,可以使用Array.isArray()函数。
Array.isArray([]); // true
Array.isArray({}); // false
但在ECMAScript 3中,并没有这样的函数
尝试typeof
typeof([]); // 'object',肯定是不行了
typeof(new Array()); // 'object'
尝试instanceof
[] instanceof Array; // true,可行
(new Array()) instanceof Array; // true,可行
({}) instanceof Array; // false
因为存在多窗口之间的混淆问题,不建议使用instanceof
解决方案
var isArray = Function.isArray || function(o) {
return typeof o === "object" && Object.prototype.toString.call(o) === "[object Array]";
};
数组独有的特点
- 新元素添加时,自动更新length属性
- 设置length属性小于元素实际数量时截断数组
- 从Array.prototype中继承一些有用的方法
- 类属性为“Array”
类数组对象
拥有一个数据length属性和对应非负整数属性的对象
- 遍历类数组对象
var a = {}; // {}
var i = 0;
while(i < 10) {
a[i] = i * i;
i++;
}
a.length = i; // 为对象a添加属性length
对象a的构成如下
{ '0': 0,
'1': 1,
'2': 4,
'3': 9,
'4': 16,
'5': 25,
'6': 36,
'7': 49,
'8': 64,
'9': 81 }
以数组的方式遍历对象a
var total = 0;
for (var j = 0; j < a.length; j++) {
total += a[j];
}
total // 285
- 检测对象是否是类数组对象
function isArrayLike(o) {
if ( o && // o非null、undefined等
typeof o === 'object' && // o是对象
isFinite(o.length) && // o.length是有限数值
o.length > =0 && // o.length是非负数
o.length === Math.floor(o.length) && // o.length是整数
o.length < 4294967296) // o.length < 2^32
return true;
else
return false;
}
- 调用数组的原生方法
var a = {"0": "a", "1": "b", "2": "c", length: 3};
Array.prototype.join.call(a, "+"); // 'a+b+c'
Array.prototype.slice.call(a, 0); // [ 'a', 'b', 'c' ]
Array.prototype.map.call(a, function(x) {
return x.toUpperCase();
});
a // [ 'A', 'B', 'C' ]
作为数组的字符串
ECMAScript 5中类数组的字符串访问
var s = "test";
s.charAt(0); // t
s[1] // e
类数组的字符串方法
var s = "JavaScript";
Array.prototype.join.call(s, " "); // 'J a v a S c r i p t'
Array.prototype.filter.call(s, function(x) {
return x.match(/[^aeiou]/);
}).join("");
x // 'JvScrpt'
字符串是只读的,将数组的方法应用于字符串时,修改字符的处理会出错。
Array.prototype.sort(s); // [],无效