JavaScript中判断对象类型的几种方法总结

作者:闭包旅人

时间:2026-10-27

浏览:346

本文总结了JavaScript中判断对象类型的四种主要方法:typeof、instanceof、constructor属性以及Object.prototype.toString。详细分析了各方法的适用场景与局限性,特别是针对跨框架(cross-frame)场景下数组检测失效的问题,推荐了基于Object.prototype.toString.call()的健壮解决方案,该方案被jQuery等主流框架采纳。

文章目录

JavaScript对象类型检测概述

在JavaScript中,检测对象类型的常用运算符包括typeof、instanceof,以及对象的constructor属性。

typeof运算符及其局限性

1) typeof 运算符。typeof是一元运算符,返回一个表示运算数类型的字符串,例如"number"、"string"、"boolean"、"object"、"function"或"undefined"(后者常用于判断变量是否存在)。然而,typeof的能力有限,对于Date和RegExp类型的对象,它返回的都是"object"。例如:


typeof {}; // "object" 
typeof []; // "object" 
typeof new Date(); // "object" 

因此,它仅在区分对象和原始类型时有效。若要区分一种对象类型与另一种对象类型,必须使用其他方法,如instanceof运算符或对象的constructor属性。

instanceof运算符的使用

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; 
} 

constructor属性判断法

3)constructor 属性。在JavaScript中,每个对象都有一个constructor属性,它引用了初始化该对象的构造函数,常用于判断未知对象的类型。例如给定一个求知的值,通过typeof运算符来判断它是原始的值还是对象。如果是对象,就可以使用constructor属性来判断其类型。所以判断数组的函数也可以这样写:


function isArray(arr){ 
  return typeof arr == "object" && arr.constructor == Array; 
} 

跨框架检测问题与Object.prototype.toString解决方案

很多情况下,我们可以使用instanceof运算符或对象的constructor属性来检测对象是否为数组。例如很多JavaScript框架就是使用这两种方法来判断对象是否为数组类型。但是检测在跨框架(cross-frame)页面中的数组时,会失败。原因就是在不同框架(iframe)中创建的数组不会相互共享其prototype属性。例如:


<script>
window.onload=function(){
var iframe_arr=new window.frames[0].Array;
alert(iframe_arr instanceof Array); // false
alert(iframe_arr.constructor == Array); // false
}
</script>

在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


实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章