0
点赞
收藏
分享

微信扫一扫

js 数据类型分类与判断

E_topia 2022-02-16 阅读 72

目录

前言

记录点js基础,js的类型分类以及判断方法,typeof()的用法问题,以及使用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
    );
    

精准判断

  1. 想要精准判断类型,建议使用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]
     );
    
举报

相关推荐

0 条评论