那么众所周知啊,js当中的类型主要分为以下两大类:
基本类型(原始类型) string.number.boolean.undefined.null.bigInt.Symbol
引用类型(复杂类型) Array.Object.Function.Date
我们可以一看看出类型,但是node却不行,那么我们怎么能让node也可以分辨类型呢?可以试试以下几个代码:
typeof
js
typeof "John" // 返回 string
typeof 3.14 // 返回 number
typeof false // 返回 boolean
typeof [1,2,3,4] // 返回 object
typeof {name:'John', age:34} // 返回 object
typeof 132456n // 返回 bigint
typeof null // 返回 object
typeof undefined // 返回 undefined
typeof [] // 返回 object
typeof {} // 返回 object
typeof function(){} // 返回 function
结果就是:
-
typeof可以判断null以外所有的原始类型
-
typeof眼里所有的引用类型都是object,除了function
这是因为在执行时,typeof是将值转化为二进制来判断类型的,二进制前三位是000说明是引用类型,所有的引用类型二进制前三位都是000,除了function;而null转化为二进制是一串0,所以null的类型被看作是object
instanceof
这一个代码比较特殊,他只能判断引用类型的函数
js
let s = 'hello'
let num = 123
let f = true
let u = undefined
let n = null
let sy = Symbol(1)
let big = 12343242n
let arr = []
let obj = {}
let fn = function(){}
console.log(obj instanceof Object);//true
console.log(fn instanceof Function);//true
console.log(arr instanceof Array);//true
console.log(s instanceof String);//false
console.log(num instanceof Number);//false
console.log(f instanceof Boolean);//false
console.log(n instanceof Null);//报错
console.log(big instanceof BigInt);//false
要注意的是,当这串代码执行数组的时候,也会把数组认定为是对象
js
let arr = []
console.log(arr instanceof Object)//true
因为这个代码的原理是来通过隐式原型链来查找的,当判断arr是不是对象的时候,js的执行逻辑是这样的
js
arr.__proto__ === Array.prototype//√
arr.__proto__.__proto__ === Object.prototype//√
Array.isArray
这串代码只能判断是否为数组
js
const arr = []
console.log(Array.isArray(arr)); //true
console.log(Array.isArray('[]')); //false
Object.prototype.toString(x)
上面三个代码都不能完整地分辨出数据类型,但是接下来这一个是重量级的,可以判断所有类型
js
let s = 'hello'
let num = 123
let f = true
let u = undefined
let n = null
let sy = Symbol(1)
let big = 12343242n
let arr = []
let obj = {}
let fn = function(){}
console.log(Object.prototype.toString.call(s))
console.log(Object.prototype.toString.call(num))
console.log(Object.prototype.toString.call(f))
console.log(Object.prototype.toString.call(u))
console.log(Object.prototype.toString.call(n))
console.log(Object.prototype.toString.call(sy))
console.log(Object.prototype.toString.call(big))
console.log(Object.prototype.toString.call(arr))
console.log(Object.prototype.toString.call(obj))
console.log(Object.prototype.toString.call(fn))
可以看出来,这串代码被很好的辨别出来了,但是有个中括号和object,觉得碍事的话,可以在后面加个.slice(8, -1)),这样的话,最后的输出结果只有想要的数据类型
js
let s = 'hello'
console.log(Object.prototype.toString.call(s).slice(8,-1))//String
若有不对,欢迎大佬指出