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

JavaScript中判断对象类型的几种方法总结_基础知识

我们知道,javascript中检测对象类型的运算符有:typeof、instanceof,还有对象的constructor属性:
1) typeof 运算符 typeof 是一元运算符,返回结果是一个说明运算数类型的字符串。如:number,string,boolean,object,function,undefined(可用于判断变量是否存在)。 但 typeof 的能力有限,其对于date、regexp类型返回的都是object。如:
typeof {}; // object
typeof []; // object
typeof new date(); // object
所以它只在区别对象和原始类型的时候才有用。要区一种对象类型和另一种对象类型,必须使用其他的方法。如:instanceof 运算符或对象的 constructor 属。
2)instanceof 运算符。 instanceof 运算符要求其左边的运算数是一个对象,右边的运算数是对象类的名字或构造函数。如果 object 是 class 或构造函数的实例,则 instanceof 运算符返回 true。如果 object 不是指定类或函数的实例,或者 object 为 null,则返回 false。如:
[] instanceof array; // true
[] instanceof object; // true
[] instanceof regexp; // false
new date instanceof date; // true
所以,可以用instanceof运算符来判断对象是否为数组类型:
function isarray(arr){
    return arr instanceof array;
}
3)constructor 属性。 javascript中,每个对象都有一个constructor属性,它引用了初始化该对象的构造函数,常用于判断未知对象的类型。如给定一个求知的值 通过typeof运算符来判断它是原始的值还是对象。如果是对象,就可以使用constructor属性来判断其类型。所以判断数组的函数也可以这样写:
function isarray(arr){
    return typeof arr == object && arr.constructor == array;
}
很多情况下,我们可以使用instanceof运算符或对象的constructor属性来检测对象是否为数组。例如很多javascript框架就是使用这两种方法来判断对象是否为数组类型。 但是检测在跨框架(cross-frame)页面中的数组时,会失败。原因就是在不同框架(iframe)中创建的数组不会相互共享其prototype属性。例如:
复制代码 代码如下:
在ajaxian上看到了一种精确的检测方法,跨原型链调用tostring()方法:object.prototype.tostring()。可以解决上面的跨框架问题。 当object.prototype.tostring(o)执行后,会执行以下步骤: 1)获取对象o的class属性。 2)连接字符串:[object +结果(1)+] 3)返回 结果(2) 例如:object.prototype.tostring.call([]); // 返回 [object array]
object.prototype.tostring.call(/reg/ig); // 返回 [object regexp]
这样,我们就可以写一个健壮的判断对象是否为数组的函数:
复制代码 代码如下:
function isarray(arr){
    return object.prototype.tostring.call(arr) === [object array];
}
此种方法得到国外多个javascript大师的认可,在即将发布的jquery 1.3中将使用这种方法来检测数组。 prototype.js的一个维护者写了下面这个函数,用于获取对象的类型名
复制代码 代码如下:
/**
 * returns internal [[class]] property of an object
 *
 * ecma-262, 15.2.4.2
 * object.prototype.tostring( )
 *
 * when the tostring method is called, the following steps are taken:
 * 1. get the [[class]] property of this object.
 * 2. compute a string value by concatenating the three strings [object , result (1), and ].
 * 3. return result (2).
 *
 * __getclass(5); // => number
 * __getclass({}); // => object
 * __getclass(/foo/); // => regexp
 * __getclass(''); // => string
 * __getclass(true); // => boolean
 * __getclass([]); // => array
 * __getclass(undefined); // => window
 * __getclass(element); // => constructor
 *
 */
function __getclass(object){
    return object.prototype.tostring.call(object).match(/^\[object\s(.*)\]$/)[1];
};
扩展一下,用于检测各种对象类型:var is ={
    types : [array, boolean, date, number, object, regexp, string, window, htmldocument]
};
for(var i = 0, c; c = is.types[i ++ ]; ){
    is[c] = (function(type){
        return function(obj){
           return object.prototype.tostring.call(obj) == [object + type + ];
        }
    )(c);
}
alert(is.array([])); // true
alert(is.date(new date)); // true
alert(is.regexp(/reg/ig)); // true
其它类似信息

推荐信息