JavaScript中的数据类型判断

1.在js(es10)中有8种数据类型,除了Object之外都是基础数据类型。Object则是引用类型,如下图在这里插入图片描述
2.引用类型和基础类型区别
简单来说,就是在复制相同数据的时候,引用类型只是指向了同一个内存地址
而值类型只是开辟新的内存地址来存值(大概意思如图)
在这里插入图片描述
3.在开发中,总要去判断数据的类型,js也给到了判断类型的方法,比较常用的有3种
1.typeof

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

弊端是不能准确判断引用类型

2.instanceof

let animal = function() {}
let cat = new animal()
cat instanceof animal // true

let cat = new String('猫')
cat instanceof String // true

let num = 123
num instanceof Number // false

instanceof 可以判断new出来的类型
但是赋值没办法判断

Object.prototype.toString

    Object.prototype.toString.call({}) // "[object Object]"
    Object.prototype.toString.call([]) // "[object Array]"
    Object.prototype.toString.call(1) // "[object Number]"
    Object.prototype.toString.call('1') // "[object String]"
    Object.prototype.toString.call(undefined) // "[object undefined]"
    Object.prototype.toString.call(true) // "[object Boolean]"
    Object.prototype.toString.call(console.log()) // "[object Function]"
    Object.prototype.toString.call(null) // "[object Null]"
    Object.prototype.toString.call(window) // "[object Window]"
    Object.prototype.toString.call(docunment) // "[object Docunment]"

这个方法属实厉害,可以判断类型,还能判断window对象等

最后总结出一个自己的判断方法

 function getTpye(obj) {
      let tpye = typeof obj 
      if(type != 'object') { // 直接用typeof判断是不是引用类型,不是直接返回
        return type
      } else {
        return  Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1')
         //使用正则替换字符串无用的部分 正则的含义,匹配[object Xxxxx]这个中Xxxx的值,并取出来
      }      
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值