须要检测是不是 number string boolean undefined function
应用typeOf 检测 是有局限性的 比方 数组、对象等援用类型检测进去都是Object
console.log(typeOf 123) // Numberconsole.log(typeOf '123') // String console.log(typeOf NaN) // Numberconsole.log(typeOf true) // Booleanconsole.log(typeOf undefined) // Undefinedconsole.log(typeOf function(){}) // Functionconsole.log(typeOf null) // Objectconsole.log(typeOf {}) // Objectconsole.log(typeOf []) // Object
应用 instanceof 检测 某个对象是否属于某个类的实例 然而检测 数组、对象、函数 等援用类型检测进去也是Object
console.log({}.instanceof Object) // trueconsole.log([].instanceof Array) // trueconsole.log(123.instanceof Number) // 报错
应用 construct 检测 能够依据原型对象检测
console.log({}.construct === Object) // trueconsole.log([].construct === Array) // trueconsole.log(123.construct === Number) // 报错
目前精确的检:Object.prototype.toString.call()
console.log(Object.prototype.toString.call(123)) // [object Number]console.log(Object.prototype.toString.call('ok')) // [object String]console.log(Object.prototype.toString.call(true)) // [object Boolean]console.log(Object.prototype.toString.call([]) // [object Array]console.log(Object.prototype.toString.call({}) // [object Object]console.log(Object.prototype.toString.call(function(){}) // [object Function]console.log(Object.prototype.toString.call(/abc/) // [object RegExp]console.log(Object.prototype.toString.call(null) // [object Null]console.log(Object.prototype.toString.call(undefined) // [object Undefined]let d= new Date()console.log(Object.prototype.toString.call(d) // [object Date]let s = Symbolconsole.log(Object.prototype.toString.call(s) // [object Symbol]
instanceof 有余:
- 能够检测出援用类型,然而检测不出根本类型
- 所有利用类型,都是Object的实例
- 能够人为批改原型链,导致检测的后果不准缺
typeOf有余:
- 能够检测出根本类型,然而检测不出援用类型,检测进去都是Object
construct有余:
- 能够检测出援用类型,然而检测不出根本类型
- 能够人为批改原型链,导致检测的后果不准缺