Javascript判断数据类型

本文介绍了前端开发中判断数据类型的四种方法:typeof操作符、instanceof关键字、Object.prototype.toString.call()方法及jQuery.type()函数,并详细说明了每种方法的特点与应用场景。

前端开发中如何判断数据类型?

  var a="abc", b=123, c=true, d=undefined, e=null, f={...}, g=[1,2], h=new Date(), i=function(){...}, j=/test/;

1. 判断原始数据类型: typeof() 

  1) typeof(a)      // string 

  2) typeof(b)      //number

  3) typeof(c)     //boolean

  4) typeof(d)    //undefined

  5) typeof(e)      //object

  6) typeof(i)    //function

  7) ...             //object

  该方法只能判断原始数据类型, 无法判断不同的引用类型/对象类型, 除function外一切引用类型(包括null)都会判别为object类型

2. instanceof   判断已知对象类型

  1) g instanceof Array    // true     ==>  g instanceof Object  //true

  2) h instanceof Date   //true

  3) i instanceof Function  //true

  4) e instanceof Object   //false   

  5) ...

  注意: null并不是以object为原型创建出来的, 本质上和object也不是一个数据类型, 所以instanceof判别为false(其问题出在typeof操作符的定义规范,规定其返回为“object”字符串)。

3. prototype  

  用法: Object.prototype.toString.call()  ==> Object.prototype.toString.call(a)  // [object String]

  各种判别结果: [object Array] [object Number] [object String] [object Undefined] [object Boolean] [object Object] [object Function] [object Null] [object Date] [object RegExp]...

  prototype输出的class属性记录了对象创建时的类型名, 且不可被更改, 但只有最原始的toString方法才能输出该class属性。

4. jQuery.type()  <==> $.type()

  jquery的方法, 与上一个方法几乎没区别, 判定结果也相同。

  如:$.type(12)    // number

  

  

 

转载于:https://www.cnblogs.com/kalkin/p/7975075.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值