JavaScript中判断对象是否为数组的多种方法解析
1. 标准数组的判断方法
在JavaScript中,声明数组最基础的方式如下所示:
var a = [];
要判断一个变量是否为数组,最直接的手段通常涉及以下代码逻辑:
a instanceof Array // 返回 true
a.constructor == Array // 返回 true
这里需要深入理解instanceof运算符。它与加减乘除等运算符类似,其基本语法结构为:
result = obj instanceof class
该运算符用于检测对象obj是否属于某个类class的实例,运算结果布尔值true或false。在JavaScript中,类的定义通过构造函数初始化,因此instance右侧的操作数必须是Function的实例,即满足class instanceof Function为true。若右侧非Function,将抛出TypeError异常。由于所有对象均为Object的实例,任何对象instanceof Object均返回true。值得注意的是,instance并非检查对象是否由特定函数构造,而是检查其原型链是否继承自该构造函数的prototype。以下示例可阐明此机制:
function Range(low, high) {
this.low = low;
this.high = high;
}
Range.prototype.constructor == Range; // true
Range.prototype = {
include: function(x){ return (x >= this.low && x <= this.high); },
exclude: function(x){ return (x < this.low && x > this.high); }
}
var r = new Range(0, 100);
r instanceof Range; // false
r instanceof Object; // true
Range.prototype.constructor == Object; // true
尽管r是通过new Range创建的,但r并非Range的实例,这正是问题的关键。在赋值前,Range.prototype.constructor指向Range;赋值后变为Object。这是因为:
Range.prototype = {
include: function(x){ return (x >= this.low && x <= this.high); },
exclude: function(x){ return (x < this.low && x > this.high); }
}
实际上等价于:
Range.prototype = new Object({
include: function(x){ return (x >= this.low && x <= this.high); },
exclude: function(x){ return (x < this.low && x > this.high); }
});
因此Range.prototype.constructor等于Object,通过new Range创建的实例自然成为Object的实例。
参考官方解释更为直观:
The instanceof operator does not actually check whether r was initialized by the Range constructor. It checks whether it inherits from Range.prototype.
JavaScript中还提供typeof函数,功能与instanceof相似,但仅返回六种基本数据类型:number、string、function、object、undefined、boolean。超出这六类的均返回object,故typeof([])返回object而非array。
另一个相关语法是constructor,它返回对象的构造函数:
var a = [];
a.constructor; // Array
构造函数用于对象初始化,需通过new调用。若对象为Array,其constructor应为Array。自定义类可能修改prototype中的constructor,因此结果不一定可靠。
2. 伪数组的判断方法
JavaScript中存在一种伪数组,支持类似Array的遍历,拥有length属性获取长度,且可通过[]下标访问元素。JQuery对象即为典型伪数组,如下图所示:
判断伪数组的关键在于检测是否存在length属性以及基本的数组操作函数splice。判断方法如下:
var is_array = function(value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
propertyIsEnumerable用于判断length属性是否可枚举。原生String对象也有类似Array的效果,但不能视为Array对象,因此需判断typeof value == "object",因为String对象的typeof返回string。