法一:typeof
typeof undefined // "undefined"
typeof false // "boolean"
typeof 'aaa' // "string"
typeof 123 // "number"
typeof {} // "object"
typeof [] // "object"
typeof null // "object"
typeof function(){} // "function"
可以发现当数据是 object,array,null 时,全部返回 object 类型。所以这个判断方法不太好。
法二:instanceof
instanceof 是通过检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
"aaa" instanceof String // false
new String("aaa") instanceof String // true
new Date() instanceof Date // true
({}) instanceof Object // true
[] instanceof Array // true
[] instanceof Object // true
比较好用,但是也有一些小问题,比如 Array 和 Object 都出现在 [] 的原型链上,可能会将 [] 误认为 Object 类型。
法三:toString.call() 最靠谱
toString.call(undefined) // "[object Undefined]"
toString.call(false) // "[object Boolean]"
toString.call('aaa') // "[object String]"
toString.call(123) // "[object Number]"
toString.call({}) // "[object Object]"
toString.call([]) // "[object Array]"
toString.call(null) // "[object Null]"
toString.call(function(){}) // "[object Function]"
可以根据返回的字符串判断是哪种类型。
法四:constructor 比较常用
const flg = true;flg.constructor === Boolean // true
const aaa = 'aaa';aaa.constructor === String // true
const num = 123;num.constructor === Number // true
const obj = {};obj.constructor === Object // true
const arr = [];arr.constructor === Array // true
const fun = function(){};fun.constructor === Function // true
但是这种方式仍然有个弊端,就是 constructor 所指向的的构造函数是可以被修改的。
本文介绍了JavaScript中四种数据类型的判断方法。包括typeof,但其对object、array、null判断不准确;instanceof通过检测构造函数属性判断,但可能误判;toString.call()最靠谱,可根据返回字符串判断;constructor较常用,但构造函数可被修改。
792





