关于javascript:总结全面的监测数据类型的方法

须要检测是不是 number string boolean undefined function

应用typeOf 检测 是有局限性的 比方 数组、对象等援用类型检测进去都是Object

console.log(typeOf 123) // Number
console.log(typeOf '123') // String 
console.log(typeOf NaN) // Number
console.log(typeOf true) // Boolean
console.log(typeOf undefined) // Undefined
console.log(typeOf function(){}) // Function

console.log(typeOf null) // Object
console.log(typeOf {}) // Object
console.log(typeOf []) // Object

应用 instanceof 检测 某个对象是否属于某个类的实例 然而检测 数组、对象、函数 等援用类型检测进去也是Object

console.log({}.instanceof Object) // true
console.log([].instanceof Array) // true
console.log(123.instanceof Number) // 报错

应用 construct 检测 能够依据原型对象检测

console.log({}.construct === Object) // true
console.log([].construct === Array) // true
console.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 = Symbol
console.log(Object.prototype.toString.call(s) // [object Symbol]

instanceof 有余:

  • 能够检测出援用类型,然而检测不出根本类型
  • 所有利用类型,都是Object的实例
  • 能够人为批改原型链,导致检测的后果不准缺

typeOf有余:

  • 能够检测出根本类型,然而检测不出援用类型,检测进去都是Object

construct有余:

  • 能够检测出援用类型,然而检测不出根本类型
  • 能够人为批改原型链,导致检测的后果不准缺

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理