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的值,并取出来
}
}