数据类型的检测

typeof

最常用的一种

console.log(typeof 1)           //'number'
console.log(typeof '1')         //'string'
console.log(typeof undefined)   //'undefined'
console.log(typeof true)        //'boolean'
console.log(typeof Symbol())    //'symbol'
console.log(typeof null)        //'object'
console.log(typeof [])          //'object'
console.log(typeof {})          //'object'
console.log(typeof console)     //'object'
console.log(typeof console.log) //'function'

前6个为基本类型。

null的typeof为object可以理解为js的一个bug,不代表null为引用类型,null本身也不是对象。判断null的方法,可以直接通过 === null。

引用类型使用typeof判断的话,除了function可以判断出来,其余都是'object',是无法准确判断的。

instanceof

原型链查找

let Person = function () { }
const p1 = new Person()
console.log(p1 instanceof Person)   //true

手写instanceof原理代码

function myInstanceof(left, right) {
    //基础类型直接返回false
    if (typeof left !== 'object' || left === null) return false

    let proto = Object.getPrototypeOf(left)
    while (true) {
        if (proto === null) return false
        if (proto === right.prototype) return true
        proto = Object.getPrototypeOf(proto)
    }
}

myInstanceof([], Array) //true

Object.prototype.toString

统一返回格式为'[object Xxx]'的字符串。其中Xxx(首字母是大写,typeof是小写)就是对象的类型。

对于Object对象,直接调用toString。其他对象,需要通过call调用。

console.log(Object.prototype.toString({}))                      //'[object Object]'
console.log(Object.prototype.toString.call({}))                 //结果同上,加了call
console.log(Object.prototype.toString.call(1))                  //'[object Number]'
console.log(Object.prototype.toString.call('1'))                //'[object String]'
console.log(Object.prototype.toString.call(true))               //'[object Boolean]'
console.log(Object.prototype.toString.call(undefined))          //'[object Undefined]'
console.log(Object.prototype.toString.call(null))               //'[object Null]'
console.log(Object.prototype.toString.call(function () { }))    //'[object Function]'
console.log(Object.prototype.toString.call(new Date()))         //'[object Date]'
console.log(Object.prototype.toString.call(/123/g))             //'[object RegExp]'
console.log(Object.prototype.toString.call([]))                 //'[object Array]'
console.log(Object.prototype.toString.call(document))           //'[object HTMLDocument]'
console.log(Object.prototype.toString.call(window))             //'[object Window]'

实现全局通用的数据类型判断方法

function getType(obj) {
    let type = typeof obj
    if (type !== 'object') {
        return type
    }
    return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1').toLowerCase()
}

console.log(getType([]))    //'array'

相关:判断数组的方法

posted @ 2021-07-19 11:19  懒懒同学  阅读(33)  评论(0编辑  收藏  举报