如何准确判断变量的数据类型

基础数据类型

js数据类型:字符串、数字、布尔、数组、对象、Null、Undefined

"string"  //string

1  //number

true  //boolen

[]  //array

{}  //object

null  //null

undefined  //undefined

常规判断数据类型方法

typeof:

1 typeof 'string'    //string
2 typeof 1    //number
3 typeof true    //boolean
4 typeof function() {}    //functuion
5 typeof {}    //object
6 typeof undefined    //undefined
7 typeof []    //object
8 typeof new Number    //object
9 typeof new String    //object

可以看到,通过typeof并不能全部的判断所有的数据类型,对于数组,以及通过原型new出来的字符串数字类型,依然呈现的是object

instanceof:

({}) instanceof Object    //true
[] instanceof Array    //true
1 instanceof Number    //false
true instanceof Boolean    //false
'string' instanceof String    //false
new Number instanceof Number    //true
new Srting instanceof String    //true
new Array instanceof Array    //true

和typeof不一样的是,instanceof能够判断出来符合类型的数据,但是这种判断方式比较繁杂,而且对于null这种特殊的情况,判断出来也是有误的

1 typeof null    //object
2 null instanceof Object    //false

toString:

1 ({}).toString()    //[object Object]
2 (new Error).toString()    //[object Error]

但是,很多对象,都重写toString方法,所以通过这种方法确实能够判断出来很少一部分变量类型,但是并不全面

1 toString.call({})    //[object Object]
2 toString.call(new Number)    //[object Number]
3 toString.call(1)    //[object Number]
4 toString.call(new String)    //[object String]
5 toString.call('string')    //[object String]
6 toString.call(new Boolean)    //[object Boolean]
7 toString.call(true)    //[object Boolean]
8 toString.call(null)    //[object Window]
9 toString.call(undefined)    //[object Window]

通过调用系统默认的toString方法,能够确认很多数据类型,但是null和undefined又出了问题,无法判断出来,因为null和undefined在作为参数的时候,相当于没有参数,而toString()默认没有参数调用的时候,相当于window.toString()会返回[object Window]

总的说来,要判断一个变量的数据类型,还是要进行综合的使用以上的方法

 1 function type(obj) {
 2   if(obj == null || obj == undefined) {
 3     return obj + '';
 4   } else {
 5     return toString.call(obj).replace(/\[.*\s|\]$/g, '');
 6   }
 7 }
 8 
 9 type(null)    //null
10 type(undefined)    //undefined
11 type(1)    //Number
12 type(new Number)    //Number
13 type(true)    //Boolean
14 type({})    //Object
15 type('123')    //String
16 type(new String)    //String

这种判断相对来说比较全面,当然,也有特例,type()返回undefined

原文地址:https://www.cnblogs.com/timmer/p/6343908.html