4.1 Typeof
可以判断基本类型数据类型,除了null以外
typeof 1 // 'number'typeof '1' // 'string'typeof undefined // 'undefined'typeof true // 'boolean'typeof Symbol() // 'symbol'typeof b // b 没有声明,但是还会显示 undefined
在判断引用类型时,除了function其他都会返回object
typeof [] // 'object'typeof {} // 'object'typeof console.log // 'function'
在判断null的时候会返回object,这是存在一个很久的bug
typeof null // 'object'
出在这个bug的原因是JavaScript创立之初使用的操作系统是32位操作系统,为了性能使用的低位存储, 000 开头表示为对象,而 null 全是零,所以会返回 object
4.2 instanceof
instanceof 可以正确的判断对象的类型,其内部机制是通过判断对象的原型链中能不能找到其对象构造函数或对象的 prototype
function Car(make, model, year) {this.make = make;this.model = model;this.year = year;}const auto = new Car('Honda', 'Accord', 1998);console.log(auto instanceof Car);// expected output: trueconsole.log(auto instanceof Object);// expected output: true
手动实现:
function instaceOf(left, right) {let proto = left.__proto__let prototype = right.prototypewhile(true) {if (proto === null) {return false}if (proto === prototype) {return true}proto = proto.__proto__}}
4.3 Object.prototype.toString.call()
可以利用toString()方法返回的字符串正确判断数据的类型,不论是基本类型数据还是引用类型数据,最为靠谱的方法。
function getType(obj) {const strs = Object.prototype.toString.call(obj).split(' ')if (strs.length > 1) {let typeStr = strs[1]typeStr = typeStr.substring(0, typeStr.length - 1)return typeStr.toLowerCase()}}getType({}) // objectgetType('a') // stringgetType(true) // booleangetType(1) // numbergetType(null) // null
