js数据类型的判断

118 阅读1分钟
  • typeOf
var str = 1
typeOf str
返回 number

判断区分不了Array,Object

  • instancof
var arr = []
arr instanceof Array
返回true

instanceof 是根据对象的constructor判断的,更改了constructor属性就会判断错误

  • Object.prototype.toString.call()
var arr = []
Object.prototype.toString.call(arr)
返回 "[Object Array]"
function DataType(n){
    var reg = /\[object (\w+)\]/
    reg.test(Object.prototype.toString.call(n))
    return RegExp.$1
}