javascript判断数据类型

  1. 数据类型的分类
  • 7大基本数据类型
  • 注意没有NaN(恶心东西)
  • null typeof(null) ==object 历史bug
    MDN
类型typeof
undefinedtypeof instance === “undefined”
Booleantypeof instance === “boolean”
Numbertypeof instance === “number”
Stringtypeof instance === "string
BigInt(MDN)typeof instance === “bigint”
Symboltypeof instance === “symbol”
nulltypeof instance === “object”(bug)
  • 复杂数据类型Object
  • 包括Array、Function、Date、RegExp、Error、Arguments
  1. typeof(MDN)
        let {
            log
        } = console
        let a = {}

        function b() {}
        let c = []
        log(typeof(NaN))
        log(typeof(a)) //object
        log(typeof(b)); //function
        log(typeof(c)); //object
        log(typeof(NaN)) //number
        log(typeof(Function))//function

可以看出大多数都检测出来了(null==object)
但:

typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
  1. instanceof(MDN)检测自定义类型

object instanceof constructor

检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上

  • instanceof 可以准确判断对象(引用)类型,但是不能准确检测原始类型。
  • 由于我们可以随意修改原型的指向导致检测结果不准确,所以这种方法是不安全的。
function Foo() {
}

Object instanceof Object // true
Function instanceof Function // true
Function instanceof Object // true
Foo instanceof Foo // false
Foo instanceof Object // true
Foo instanceof Function // true

这里看懂了原型链也就懂了,可以看

  1. Object.prototype.toString.call(obj)检测对象的类型

Object.prototype.toString() 返回 “[object type]”

Object.prototype.toString.call(obj)

改变它的this指向,将 this 指向要检测的值,即可返回当前检测值的信息。

		log(Object.prototype.toString([])) //[object,object]
        log(Object.prototype.toString.call([])) //[object,array]
        log(Object.prototype.toString.call(null))//[object,Null]
        log(Object.prototype.toString.call(undefined))//[object,undefined]
        //[object,undefined]没有都号
  1. constructor
  • 除了 null 和 undefined,constructor 可以正确检测出原始类型和对象(引用)类型。
  • 由于我们可以随意修改 constructor 导致检测结果不准确,所以这种方法是不安全的。
  		log([].constructor) //f Array(){}
            //log(undefined.constructor)//报错
        console.log(null.constructor);报错
  1. 封装:typeof+toString()
const getType = function(obj) {
    let type = typeof obj
    if (type !== 'object') {
        return type
    }
    //return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1').toLowerCase()
    return Object.prototype.toString.call(obj).split(' ')[1].replace(']', '').toLowerCase()
}

另外判断数组的方法有了吧。

		console.log([] instanceof Array)
        console.log(getType([]) == 'array');
        console.log([].constructor == Array);
        console.log(Array.isArray([]));

NaN 用Number.isNaN()把,看到就烦(不咋用)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值