数据类型

1.原始值检测

    (1)string、number、boolean、undefined、symbol检测使用typeof 

    (2)null检测使用===或!==

2.引用值检测

    (1)Date、Error、RegExp等内置js类型和自定义类型用instanceof

    (2)Function检测:myFun instanceof Function(跨帧问题),typeof myFun会返回Function(可跨帧) 

      (3)数组检测

function isArray(value){
    if(typeof Array.isArray){ // es5提供Array.isArray()方法
        return Array.isArray(value)
    } else {
        Object.prototype.toString.call(value) === '[Object Array]'
    }
} 

3.其它

   (1) typeof null = object,但null 不是object,历史遗留问题,000 开头代表是对象,null 表示为全零,所以将它错误的判断为 object 

   (2) instanceof检测构造器和原型链,everything instanceof object都为true

   (3)instanceof会因为浏览器帧(frame)不同,帧A的实例在instanceof 帧B是同一对象会返回false,每个帧有其各自的构造函数,这是最早的跨域问题

   (4)typeof document.getElementById ie9及以上返回Function,ie8没有将Dom实现为内置Js方法,不返回Function

   (5)检测dom的方法使用 if('querySelectorAll' in document)  其它情况的函数使用typeof

     (6)  数据类型:基本类型:Number、String、Boolean、null、undefined、Symbol、Bigint,引用类型:Object

   (7)Object.prototype.toString.call()    

console.log(Object.prototype.toString.call(123))  // [object Number]
console.log(Object.prototype.toString.call('123')) // [object String]
console.log(Object.prototype.toString.call(true)) // [object Boolean]
console.log(Object.prototype.toString.call(Symbol(123))) // [object Symbol]
console.log(Object.prototype.toString.call(null)) // [object Null]
console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call(function (){})) // [object Function]
console.log(Object.prototype.toString.call({})) // [object Object]
console.log(Object.prototype.toString.call([])) // [object Array]

console.log(Object.prototype.toString.call(new Error())) // [object Error]
console.log(Object.prototype.toString.call(/\d/)) // [object RegExp]
console.log(Object.prototype.toString.call(Date())) // [object String]
console.log(Object.prototype.toString.call(new Date())) // [object Date]

(function(){
console.log(Object.prototype.toString.call(arguments)) // [Object Arguments] 浏览器提供
})()
console.log(Object.prototype.toString.call(document)) // [Object HTMLDocument] 浏览器提供

 

const arr = []
arr instanceof Array // true
arr instanceof Object// true

const obj = {}
arr instanceof Object// true

 

posted @ 2021-08-03 19:48  卷叶小树  阅读(29)  评论(0编辑  收藏  举报