JavaScript判断变量的类型(判断基本类型、判断引用类型)

1. 通过typeof来判断

2. 通过instanceof来判断 或 通过constructor来判断

3. null直接全等判断即可

4. 万能判断方式:Object.prototype.toString.call()

 

1. 通过typeof来判断

typeof undefined // undefined 
typeof 1 // number 
typeof '1' // string 
typeof true // boolean 
typeof function() {} // function 
typeof Symbol() // symbol

// 以下类型需要别的方式判断
typeof null // object 
typeof {} // object 
typeof [] // object

2. 通过instanceof来判断 或 通过constructor来判断

// 以下这个不准确,因为instanceof会去找原型链。而引用类型的__proto__最终都会指向Object.prototype。
obj instanceof Object // true
[] instanceof Object // true
new Date() instanceof Object // true
new RegExp() instanceof Object // true

// 判断对象更好的方式:
obj.constructor === Object // true

// 判断数组
[] instanceof Array // true
[].constructor === Array // true

// 判断日期对象
new Date() instanceof Date // true
new Date().constructor === Date // true

// 判断正则表达式对象
new RegExp() instanceof RegExp // true
new RegExp().constructor === RegExp // true

3. null直接全等判断即可

null === null // true

4. 万能判断方式:Object.prototype.toString.call()

// 引用类型
Object.prototype.toString.call({}) // [object Object]
Object.prototype.toString.call([]) // [object Array]
Object.prototype.toString.call(new Date()) // [object Date]
Object.prototype.toString.call(new RegExp()) // [object RegExp]
Object.prototype.toString.call(function(){}) // [object Function]

// 基本类型
Object.prototype.toString.call(null) // [object Null]
Object.prototype.toString.call(undefined) // [object Undefined]
Object.prototype.toString.call(true) // [object Boolean]
Object.prototype.toString.call('1') // [object String]
Object.prototype.toString.call(1) // [object Number]
Object.prototype.toString.call(Symbol()) // [object Symbol]

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值