1.typeof 只能判断基本数据类型
typeof NaN 为number
typeof function a(){} 为 function
typeof null 为object
typeof Array 为object
typeof 可以对JS基础数据类型做出准确的判断,而对于引用类型返回的基本上都是object,
2.instanceof 只能用来判断两个对象是否属于原型链的关系, 而不能获取对象的具体类型。
var a=null
a instanceof Null 为true
3.使用Object.prototype.toString.call() 判断简单数据类型和复杂数据类型(推荐)
const a=null
Object.prototype.toString.call(a) 为 [object Null]
toString是Object原型对象上的一个方法,该方法默认返回其调用者的具体类型,
4.constructor 能判断引用数据类型 需要特别注意的是null和undefined没有constructor属性。
var a=[12,145,1]
a.constructor===Array 为true
null和undefined是无效的对象,因此是不会有constructor存在的,这两种类型的数据需要通过typeof来判断。 JS对象的constructor是不稳定的,这个主要体现在自定义对象上,当开发者重写prototype后,原有的constructor会丢失,constructor会默认为Object 。
5.Array.isArray()判断是否为数组
var a=[1,4]
Array.isArray(a) 为true
6.===
可以判断 undefined,null