js中准确判断数据类型的方法
一 通用的typeof 方法
typeof ture 输出 Boolean
typeof 123 输出 number
.....
但是 typeof 无法判断 null underfind 数组 和 对象类型 因为都返回 object
二、Object.prototype.toString.call();
var gettype=Object.prototype.toString
gettype.call('aaaa') 输出 [object String]
gettype.call(2222) 输出 [object Number]
gettype.call(true) 输出 [object Boolean]
gettype.call(undefined) 输出 [object Undefined]
gettype.call(null) 输出 [object Null]
gettype.call({}) 输出 [object Object]
gettype.call([]) 输出 [object Array]
gettype.call(function(){}) 输出 [object Function]
封装一下
function type(data){
return Object.prototype.toString.call(data).slice(8,-1).toLowerCase;
}
三 jQery.type()或者$.type();
如果对象是undefined或null,则返回相应的“undefined”或“null”。
jQuery.type( undefined ) === "undefined"
jQuery.type() === "undefined" jQuery.type( window.notDefined ) === "undefined"
jQuery.type( null ) === "null"
如果对象有一个内部的[[Class]]和一个浏览器的内置对象的 [[Class]] 相同,我们返回相应的 [[Class]] 名字。
jQuery.type( true ) === "boolean"
jQuery.type( 3 ) === "number"
jQuery.type( "test" ) === "string"
jQuery.type( function(){} ) === "function"
jQuery.type( [] ) === "array"
jQuery.type( new Date() ) === "date"
jQuery.type( new Error() ) === "error" // as of
jQuery 1.9 jQuery.type( /test/ ) === "regexp"
其他一切都将返回它的类型“object”。
四 还可以用 instanceof判断已知的对象类型的方法
注意:instanceof 后面一定要是对象类型 ,并且大小写不能错,该方法适合一些条件选择和方法
比如: data.instanceof===Function 返回ture
但: data.instanceof ===function 返回false
五根据对象的constructor判断
data.constructor ===Array 返回布尔值
注意:constructor 在类继承时会出错
eg:
function A(){}; function B(){};
A.prototype = new B(); //A继承自B var aObj = new A();
alert(aobj.constructor === B) -----------> true;
alert(aobj.constructor === A) -----------> false; 而instanceof方法不会出现该问题,对象直接继承和间接继承的都会报true:
alert(aobj instanceof B) ----------------> true;
alert(aobj instanceof B) ----------------> true;
言归正传,解决construtor的问题通常是让对象的constructor手动指向自己:
aobj.constructor = A; //将自己的类赋值给对象的constructor属性
alert(aobj.constructor === A) -----------> true;
alert(aobj.constructor === B) -----------> false; //基类不会报true了;
最新文章
- C#学习总结之集合
- Python—操作redis
- sql sever获取数据库还原时间语句
- C++虚函数表
- 【转】CwRsync简介
- TypeScript:基本类型和接口
- tomcat PermGen space
- activiti基础操作
- SET QUOTED_IDENTIFIER ON
- [转] Hive 内置函数
- 卓尼斯ZT-180评測
- onActivityResult不起作用?可能是和你的launchMode有关!
- JAVA中代理模式
- power designer的安装
- Xilinx FPGA用户约束文件(转自xilinx ISE 开发指南
- day9:vcp考试
- Unity3d--->; IEnumerator
- 【转】TCP/IP详解学习笔记(一)
- iOS导航栏的正确隐藏方式
- java工具类-读配置文件
热门文章
- java数组声明和变式--record1
- 雷林鹏分享:C# 索引器(Indexer)
- LeetCode--191--位1的个数
- 一个登陆浏览api接口; 其他相关: Form_with参数的不同写法; 简单使用curl。
- (转)nginx做转发时,带'_'的header内容丢失
- UVA-10726 Coco Monkey(递推)
- HDU-1548 A strange lift(单源最短路 或 BFS)
- 怎样解决IIS6.0上传文件限制的问题?
- SecureCRT的脚本+快捷键设置
- VC++ 报错:Heap corruption detected