js 数据类型分类与判断(typeof、instanceof、Object.prototype.toString.call)

513 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

前言

记录js的类型分类以及判断方法,typeof、instanceof的用法以及存在的问题,最后介绍使用Object.prototype.toString.call()精准判断类型的方法。

js类型

  1. js有许多种内置类型,其中内置类型又分为两类,基本数据类型复杂==对象(Object)类型

  2. 基本数据类型:NullUndefinedNumberStringBooleanSymbelBigInt。(截至2022/2/16,将来或许会引入更多的基本数据类型,就像Symbel、BigInt就是比较新引入的,原来只有五大基本数据类型)

typeof

  1. 测试基本数据类型:记结论,除了null会被判断为object其他基本类型都可以判断出来,因此不能用于判断null
    console.log(
       typeof null,// object
       typeof 123,//或 Number(123),// number
       typeof undefined,// undefined
       typeof "str",//或 String('str'),// string
       typeof true,//或 Boolean(true)// boolean
       typeof Symbol(1),// symbol
       typeof 12345678910n,//或 BigInt(12345678910),// bigint
     );
    
  2. 测数组、对象、内置对象、new函数声明对象、函数等复杂对象类型:记结论,除了函数会被正确判断为function,其他全是object,因此不能用于判断除了函数之外的复杂的类型,都不能用typeof区分开来。
    console.log(
      typeof [],//object
      typeof {},//object
      typeof Math,//object
      typeof new String(),//object
      typeof (() => {}),//function
    );
    

instanceof

使用

  1. 首先明确instanceof不能判断基本数据类型,且不能直接尝试得到你想要判断的内容的类型,只能够尝试判断是否是某种类型

  2. 我们能够使用它去判断是否是某个复杂对象类型。

console.log(
    [] instanceof Array, //true
    {} instanceof Object, //true
    new Date() instanceof Date, //true
    (() => {}) instanceof Function, //true
)
  1. 因为它的原理是原型链,所以存在一个问题,就是Object的原型作为原型链的终点,js的复杂类型本质也都是对象,因此判断他们是否是对象,也都为true。
console.log(
    [] instanceof Object, //true
    {} instanceof Object, //true
    new Date() instanceof Object, //true
    (() => {}) instanceof Object, //true
)

手写一个简单的instanceof

  • instanceof原理是判断前一个对象的原型链上是否有后一个对象的原型,因此我们遍历前一个对象的原型链进行判断即可
const instanceof2 = (obj, con) => {
    while (obj) {
        if (obj.__proto__ === con.prototype) {
            return true
        } else {
            obj = obj.__proto__
        }
    }
    return false
}

console.log(instanceof2(new String('123'), String)) // true
console.log(instanceof2(new String('123'), Object)) // true

精准判断

  • .想要精准判断类型,建议使用Object.prototype.toString.call()
     console.log(
       Object.prototype.toString.call(null), //[object Null]
       Object.prototype.toString.call("123"), //[object String]
       Object.prototype.toString.call(123), //[object Number]
       Object.prototype.toString.call(undefined), //[object Undefined]
       Object.prototype.toString.call(true), //[object Boolean]
       Object.prototype.toString.call(Symbol(1)), //[object Symbol]
       Object.prototype.toString.call(BigInt(1)), //[object BigInt]
       Object.prototype.toString.call(() => {}), //[object Function]
       Object.prototype.toString.call([]), //[object Array]
       Object.prototype.toString.call({}), //[object Object]
       Object.prototype.toString.call(Math), //[object Math]
       Object.prototype.toString.call(new String()) //[object String]
     );
    

尾言

如果觉得文章对你有帮助的话,欢迎点赞收藏哦,有什么错误或者意见建议也可以留言,感谢~