Javascript判断数据类型

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

  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