JavaScript 类型判断

6 篇文章 0 订阅

1.typeof

可作为 区分大的不同类型
可区分 类型: 字符串 、对象、布尔、function 、number、undefined
不能区分 : 对象里的详细类型; 例如 对象里的 数组、null 等等 (写在 3 内容里了)
特殊区分:能区分’undefined’,不能区分null(null是object) ===> typeof xxx

Value               Class      Type 
-- ------------------------------------------
"foo"               String     string
new String("foo")   String     object
1.2                 Number     number
new Number(1.2)     Number     object
true                Boolean    boolean
new Boolean(true)   Boolean    object
new Date()          Date       object
new Error()         Error      object
[1,2,3]             Array      object
new Array(1, 2, 3)  Array      object
new Function("")    Function   function
/abc/g              RegExp     object (function in Nitro/V8)
new RegExp("meow")  RegExp     object (function in Nitro/V8)
{}                  Object     object
new Object()        Object     object

2. instanceof

只能原型链是构造函数的数据,否则判断不出来,例如:

null instanceof Object  // false,

可判断 元素 是否为 数组:

[] instanceof Array //  true 

3.Object.prototype.toString.call(xx) // [Object xx]

参考文章:https://bonsaiden.github.io/JavaScript-Garden/zh/#types.typeof

只检测 对象里的具体类型 ======== 补充 typoof 的判断

Object.prototype.toString.call([])  //  "[object Array]"
Object.prototype.toString.call( null )  // "[object Null]"

结合正则,判断是不是某种类型

 /Object/.test(Object.prototype.toString.call({}))
 /Array/.test(Object.prototype.toString.call([]))
 /Function/.test(Object.prototype.toString.call(function(){}))
 /String/.test(Object.prototype.toString.call('abc'))

由此扩展:

写一个综合的类型判断:

function types(typeData){
    if(typeof typeData !== 'object' ){
        // return `${typeData} is not 'object' type`
        return typeof typeData
    }
    _typeObj = Object.prototype.toString.call(typeData)
    return _typeObj.split(']').length > 1 ? _typeObj.split(']')[0].split(' ').length > 0 ? _typeObj.split(']')[0].split(' ')[1] : 'Object.prototype.toString.call 过滤类型的字符串有异常' : '不在 typeof 与 toString 类型判断范围内'
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值