判断数据类型方法:
1、typeof
2、instance
3、Object.prototype.toString.call()
typeof
typeof '1' // 'String'
typeof 1 // 'Number'
typeof false // 'Boolean'
typeof undefined // 'undefined'
typeof Symbol() // 'Symbol'
typeof null // 'Object'
typeof {} //'Object'
typeof [] // 'Object'
typeof Function // 'function'
typeof null 为什么是Object?
类型标签存储在单元的低位。二进制的前三位为0的话,系统将其判断为Object类型。
000:对象
1:整数
010:浮点数
100:字符串
110:布尔
instanceof
[] instanceof Array // true
({}) instanceof Object // true
(()=>{}) instanceof Function // true
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
Object.prototype.toString()
Object.prototype.toString.call('snow') // '[object String]'
Object.prototype.toString.call(1) // '[object Number]'
Object.prototype.toString.call(true) // '[object Boolean]'
Object.prototype.toString.call(Symbol()) // '[object Symbol]'
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call(undefined) // '[object Undefined]'Object.prototype.toString.call({}) // '[object Object]'
Object.prototype.toString.call([1,2]) // '[object Array]'
Object.prototype.toString.call(()=>{}) // '[object Function]'
每个对象都有一个 toString() 方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认情况下,toString() 方法被每个 Object 对象继承。如果此方法在自定义对象中未被覆盖,toString() 返回 "[object type]",其中 type 是对象的类型。
网友评论