js准确判断基本类型和引用类型的方法
2019-10-18 本文已影响0人
凛冬已至_123
Object.prototype.toString.call-准确判断变量的类型(无论是基本类型还是引用类型)
-
一定要使用
Object.prototype.toString而不是Object.toString,原因和原型链有关:
-
Object是一个function,即为Function的实例-Object.__proto__指向Function.prototype -
Object本身并没有toString方法,该方法在Object.prototype上 -
Object.toString并不能找到prototype上的toString,Object会找到__proto__指向的Function.prototype,即Object.toString找到的是Function.toString
so,只能通过Object.prototype.toString找到toString方法
- 下面看一下实例
console.log(Object.prototype.toString.call(1)) //"[object Number]"
console.log(Object.prototype.toString.call('3432')) //"[object String]"
console.log(Object.prototype.toString.call(true)) //"[object Boolean]"
console.log(Object.prototype.toString.call(undefined)) //"[object Undefined]"
console.log(Object.prototype.toString.call(null)) //"[object Null]"
console.log(Object.prototype.toString.call(()=>{})) //"[object Function]"
console.log(Object.prototype.toString.call({})) //"[object Object]"
console.log(Object.prototype.toString.call([])) //"[object Array]"
console.log(Object.prototype.toString.call(new Date())) //"[object Date]"
-
typeof对于null和引用类型判断不准确 -
instanceof不适用于基本数据类型
所以,这种方法更准确