数据类型判断

本文介绍了JavaScript中数据类型的判断方法,包括使用typeof、instanceof及constructor属性等,并对比了各自的适用场景与限制。
  1. List item

数据类型判断

  • typeof
        typeof 666,  // Number,
        typeof 'abc',  // String,
        typeof true ,// Bolearn,
        typeof {} , // object,
        typeof [] , // object,
        typeof null ,  // object ,
        typeof undefined, //undefined
        typeof /^[a-zA-Z]{5,20}$/   // object
        typeof new Date() ,  //object
        typeof function(){} ,//function

基本数据类型中:null 。引用数据类型中的:Array,Object,Date,RegExp。不可以用typeof检测。都会返回object

  • instanceof
     100 instanceof Number,  //false       
     'abc' instanceof String,  //false
     true instanceof Boolean,//false
    //  null instanceof Null, // 报错
    //  undefined instanceof Undefined, // 报错

     {} instanceof Object,//true
     [] instanceof Array,//true
     new Date() instanceof Date,//true
     /666/ instanceof RegExp,//true
     function(){} instanceof Function ,//true

也就是instanceof 可以检测引用数据类型 但不能检测基本数据类型 并且检测 null和undefined的时候还会报错

  • constructor 属性返回对创建此对象的 Date 函数的引用。
 var arr = [1, 2]
    var nub = 1123
    var obj = {}
    var und = undefined
    var nul = null
    var str = 'abc'
    var reg = /^[a-zA-Z]{5,20}$/
    // undefined和null没有constructor属性

consol.log(
        arr.constructor == Array,
        nub.constructor == Number,
        obj.constructor == Object,
        // und.constructor==Undefined,  //报错
        // null.constructor==Null,  // 报错
        str.constructor == String,
        reg.constructor == RegExp,
)

也就是null和undefined不能用此方法检测

  • 使用Object.prototype.toString.call()检测对象类型
 var  nb=Object.prototype.toString
nu.call(123)// [object Number]
nu.call([1,2])// [object Array]
nu.call({a:1})// [object Object]
nu.call(/^[a-zA-Z]{5,20}$/)// [object RegExp]
nu.call(asd)// [object String]

这个还是可行的

  • jquery.type()
 jquery.type(123)   // number 
 jquery.type([1,2])   // array
 jquery.type({a:1})   // object
 jquery.type(abc)   // string
 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值