第一种方法是typeof,但是这种方法并不靠谱,它无法准确的判断一个数据类型是数组还是对象还是null。只可以进行模糊的判断。
console.log(typeof 2)//number
console.log(typeof true)//bollean
console.log(typeof [1,2,3])//object
console.log(typeof function(){})//function
console.log(typeof ({a:1,b:2}))//object
console.log(typeof null)//object
console.log(typeof undefined)//undefinde
//使用typeof进行数据类型判断是无法正确判断Array和Object以及null的,
//因为从上面可以看到Array的typeof也是Object
第二种方法是instaceof,这个方法是用来判断一个实例是否属于一个类。由于在JS里数组和函数的原型继承了对象Obejct的,所以这种方法其实也不靠谱。另外String和Bollean还有Number也都无法进行准确的判断,原因是这些都是基本数据类型,并不是实例。并且,要注意的是null和undefined使用instanceof关键字会报错。
但是假如使用构造函数的方式创建一个String的实例或者Number的实例,返回的结果又是true。具体情况看下面的代码吧。
console.log(1 instanceof Number)//false
console.log(true instanceof Boolean)//false
console.log("hi" instanceof String)//false
var str = new String("1")
console.log(str instanceof String)//true
var num = new Number(1)
console.log(num instanceof Number)//true
console.log([1,2] instanceof Array)//true
console.log({a:1,b:2} instanceof Object)//true
console.log(function(){} instanceof Function)//true
console.log([1,2] instanceof Object)//true
console.log(function(){} instanceof Object)//true
第三个引出的方式是constructor,这个是原型上的一个属性,所有实例都可以访问,它的指向是类(构造函数)。借助他我们也可以判断数据类型。
其实从上面我们很容易可以看出,无论是typeof还是instanceof都难以判断Array和Object,我们先来看看constructor有没有解决这个痛点。
console.log([1,2,3].constructor==Array)//true
console.log([1,2,3].constructor===Object)//false
console.log(function(){}.constructor===Function)//true
console.log(function(){}.constructor===Object)//false
并且,基本数据类型也可以访问到constructor属性,并且返回的结果是正确的。
console.log(true.constructor===Boolean)//true
console.log("hi".constructor===String)//true
console.log((1).constructor===Number)//true
但是这种方法也不保险,应为原型对象是可以改变的。比如说这样:
function Fn(){}
Fn.prototype= new Array()
var f = new Fn()
console.log(f.constructor==Fn)//false
console.log(f.constructor==Array)//true
最后一个全能并且无惧修改原型对象的方法就是......
console.log(toStr.call("hi"))//[object String]
console.log(toStr.call(1))// [object Number]
console.log(toStr.call(true))//[object Boolean]
console.log(toStr.call([1,2,3]))//[object Array]
console.log(toStr.call({a:1,b:2}))//[object Object]
console.log(toStr.call(function(){}))//[object Function]
console.log(toStr.call(null))// [object Null]
console.log(toStr.call(undefined))// [object Undefined]