JS类型判断

判断数据类型方法:

  1. typeof
  2. instanceof
  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:布尔
The history of “typeof null”

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 是对象的类型。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值