找回密码
 注册
搜索
查看: 2704|回复: 0

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

[复制链接]
发表于 2013-1-2 15:24:30 | 显示全部楼层 |阅读模式
原文:http://www.cnblogs.com/flyjs/archive/2012/02/20/2360504.html

我们知道,JavaScript中检测对象类型的运算符有:typeof、instanceof,还有对象的constructor属性: 1) typeof 运算符 typeof 是一元运算符,返回结果是一个说明运算数类型的字符串。如:"number","string","boolean","object","function","undefined"(可用于判断变量是否存在)。 但 typeof 的能力有限,其对于Date、RegExp类型返回的都是"object"。如:
  1. typeof {}; // "object"
  2. typeof []; // "object"
  3. typeof new Date(); // "object"
复制代码
所以它只在区别对象和原始类型的时候才有用。要区一种对象类型和另一种对象类型,必须使用其他的方法。如:instanceof 运算符或对象的 constructor 属。 2)instanceof 运算符。 instanceof 运算符要求其左边的运算数是一个对象,右边的运算数是对象类的名字或构造函数。如果 object 是 class 或构造函数的实例,则 instanceof 运算符返回 true。如果 object 不是指定类或函数的实例,或者 object 为 null,则返回 false。如:
  1. [] instanceof Array; // true
  2. [] instanceof Object; // true
  3. [] instanceof RegExp; // false
  4. new Date instanceof Date; // true
复制代码
所以,可以用instanceof运算符来判断对象是否为数组类型:
  1. function isArray(arr){
  2.     return arr instanceof Array;
  3. }
复制代码
3)constructor 属性。 JavaScript中,每个对象都有一个constructor属性,它引用了初始化该对象的构造函数,常用于判断未知对象的类型。如给定一个求知的值 通过typeof运算符来判断它是原始的值还是对象。如果是对象,就可以使用constructor属性来判断其类型。所以判断数组的函数也可以这样写:
  1. function isArray(arr){
  2.     return typeof arr == "object" && arr.constructor == Array;
  3. }
复制代码
很多情况下,我们可以使用instanceof运算符或对象的constructor属性来检测对象是否为数组。例如很多JavaScript框架就是使用这两种方法来判断对象是否为数组类型。 但是检测在跨框架(cross-frame)页面中的数组时,会失败。原因就是在不同框架(iframe)中创建的数组不会相互共享其prototype属性。例如:
  1. <script>
  2. window.onload=function(){
  3. var iframe_arr=new window.frames[0].Array;
  4. alert(iframe_arr instanceof Array); // false
  5. alert(iframe_arr.constructor == Array); // false
  6. }
  7. </script>
复制代码
在Ajaxian上看到了一种精确的检测方法,跨原型链调用toString()方法:Object.prototype.toString()。可以解决上面的跨框架问题。 当Object.prototype.toString(o)执行后,会执行以下步骤: 1)获取对象o的class属性。 2)连接字符串:"[object "+结果(1)+"]" 3)返回 结果(2) 例如:
  1. Object.prototype.toString.call([]); // 返回 "[object Array]"
  2. Object.prototype.toString.call(/reg/ig); // 返回 "[object RegExp]"
复制代码
这样,我们就可以写一个健壮的判断对象是否为数组的函数:
  1. function isArray(arr){
  2.     return Object.prototype.toString.call(arr) === "[object Array]";
  3. }
复制代码
此种方法得到国外多个javaScript大师的认可,在即将发布的jQuery 1.3中将使用这种方法来检测数组。 prototype.js的一个维护者写了下面这个函数,用于获取对象的类型名
  1. /**
  2. * Returns internal [[Class]] property of an object
  3. *
  4. * Ecma-262, 15.2.4.2
  5. * Object.prototype.toString( )
  6. *
  7. * When the toString method is called, the following steps are taken:
  8. * 1. Get the [[Class]] property of this object.
  9. * 2. Compute a string value by concatenating the three strings "[object ", Result (1), and "]".
  10. * 3. Return Result (2).
  11. *
  12. * __getClass(5); // => "Number"
  13. * __getClass({}); // => "Object"
  14. * __getClass(/foo/); // => "RegExp"
  15. * __getClass(''); // => "String"
  16. * __getClass(true); // => "Boolean"
  17. * __getClass([]); // => "Array"
  18. * __getClass(undefined); // => "Window"
  19. * __getClass(Element); // => "Constructor"
  20. *
  21. */
  22. function __getClass(object){
  23.     return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
  24. };
复制代码
扩展一下,用于检测各种对象类型:
  1. var is ={
  2.     types : ["Array", "Boolean", "Date", "Number", "Object", "RegExp", "String", "Window", "HTMLDocument"]
  3. };
  4. for(var i = 0, c; c = is.types[i ++ ]; ){
  5.     is[c] = (function(type){
  6.         return function(obj){
  7.            return Object.prototype.toString.call(obj) == "[object " + type + "]";
  8.         }
  9.     )(c);
  10. }
  11. alert(is.Array([])); // true
  12. alert(is.Date(new Date)); // true
  13. alert(is.RegExp(/reg/ig)); // true
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|宁德市腾云网络科技有限公司 ( 闽ICP备2022007940号-5|闽公网安备 35092202000206号 )

GMT+8, 2025-6-19 03:28 , Processed in 0.016224 second(s), 15 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表