您好,欢迎访问一九零五行业门户网

js语法学习之判断一个对象是否为数组_javascript技巧

1,真正的数组的判断方法
javascript中最简单的声明数组方法为:
var a = [];
判断是否为数组的最直接的方法为:
复制代码 代码如下:
a instanceof array //true
a .constructor == array //true
这里涉及到一个instanceof语法,instanceof是一个云算符,与+-*/一样,它的语法如下:
result = obj intanceof class
是用来判断一个对象是否是某个class的一个实例,运算结果返回true或者false。javascript中class的定义又是通过构造函数进行初始化的,所以instanceof语法的右操作符class一定是function的实例,即class instanceof function一定为true,而且如果使用instanceof时右操作符不是function,就会抛出typeerror异常。所有对象都是object的实例,所以任何对象instanceof object都返回true。虽然我们说对象都是通过构造函数进行初始化的,但是instanceof却不是通过检查对象是否由该函数构造的,而是通过是否由构造函数的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 exclude: function(x){ return (x this.high); }
}
var r = new range(0, 100);
r instanceof range; //false
r instanceof object; //true
range.prototype.constructor == objecct; //true
这里虽然r是通过new range构造的,但是r却并不是range的实例,这就是问题所在,range.prototype赋值语句覆盖了默认的构造函数,没对prototype赋值之前range.prototype.constructor为range,赋值之后变成了object,这也好理解,因为
复制代码 代码如下:
range.prototype = {
include: function(x){ return (x >= this.low && x exclude: function(x){ return (x this.high); }
}
其实等价于:
复制代码 代码如下:
range.prototype = new object({
include: function(x){ return (x >= this.low && x exclude: function(x){ return (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,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,因为typeof一个string对象,返回的是string。
其它类似信息

推荐信息