javascript类型判断

 2023-09-05 阅读 20 评论 0

摘要:javascript中,类型判断是各大类库的基础之一。来看看是怎么实现的。 主要有三种方法: 1,满是坑的typeof (认识其坑后是一个利器)   typeof 返回6种基本类型:number, string, object, boolean, undefined, function   其中有几个很容易误导的&

javascript中,类型判断是各大类库的基础之一。来看看是怎么实现的。

主要有三种方法:

1,满是坑的typeof  (认识其坑后是一个利器)

  typeof 返回6种基本类型:number, string, object, boolean, undefined, function

  其中有几个很容易误导的:

  (1)typeof obj === 'object',你却不能真正当对象使用

if (typeof obj === 'object') {obj.a() // 这里报错
}

  (2)typeof NAN === 'number',你却不能使用它进行算术运算

if (typeof num === 'number') {num = num + 10 // 执行后num仍然是NaN
}

  (3)Safar5,Chrome7之前的版本对正则对象返回 'function'

  (4) 不能区分对象、数组、正则,对它们操作都返回'object'

 

2,遗憾的constructor 和 instanceof

  为什么说遗憾,因为在跨文档操作时候,会产生bug

// 用法
function isArray(arr){return typeof arr == "object" && arr.constructor == Array;
}
// 跨文档操作时就呵呵了
window.οnlοad=function(){
var iframe_arr=new window.frames[0].Array;
alert(iframe_arr instanceof Array); // false
alert(iframe_arr.constructor == Array); // false
}

 

3, 最后的解药:Object.prototype.toString.

  直接把jQuery.2.0.3源码贴上

class2type = {}
core_toString = class2type.toStringjQuery.each(
"Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {class2type[ "[object " + name + "]" ] = name.toLowerCase(); });type: function( obj ) {if ( obj == null ) {return String( obj );}// Support: Safari <= 5.1 (functionish RegExp)return typeof obj === "object" || typeof obj === "function" ?class2type[ core_toString.call(obj) ] || "object" :typeof obj;}

 

总结:除了自定义类型外外,组合类型基本用Object.prototype.toString这种方法。typeof方法可以用来判断boolean, undefined, string类型

 

 

  

 

转载于:https://www.cnblogs.com/pfzeng/p/4476307.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/1491.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息