js数据类型判断 前

js数据类型判断

原文链接:https://www.cnblogs.com/hahazexia/p/8886829.html

1,typeof判断

下面是常用的类型判断

console.log(
        typeof 123, //"number"
        typeof 'abc', //"string"
        typeof true, //"boolean"
        typeof [1, 2], //"object"
        typeof {}, //"object"
        typeof function () {}, //"function"
        typeof undefined, //"undefined"
        typeof null, //"object"
        typeof new Date(), //"object"
        typeof /^[a-z]$/, //"object"
        typeof new Error() //"object"
    );

代码结果可以看到,除了Function,Boolean,String,Number,Undefinde,其他判断的都是object,比较笼统,不能精确判断,这种情况不适用;

2,instanceof

  console.log(
        123 instanceof Number, //false
        'abc' instanceof String, //false
        false instanceof Boolean, //false
        [1, 2, 3] instanceof Array, //true
        {} instanceof Object, //true
        function () { } instanceof Function, //true
        undefined instanceof Object, //false
        null instanceof Object, //false
        new Date() instanceof Date, //true
        /^[a-zA-Z]$/ instanceof RegExp, //true
        new Error() instanceof Error //true
    )

Number,String,Boolean没有检测出他们的类型,不适用此方法,null,undefinde,因为他们的类型是自己本身,不是object创建出来的,所以判断也是false

3,constructor

constructor是prototype对象上的属性,指向构造函数。根据实例对象寻找属性的顺序,若实例对象上没有实例属性或方法时,就去原型链上寻找,因此,实例对象也是能使用constructor属性的。

console.log(new Number(123).constructor)
//ƒ Number() { [native code] }

可以看到它指向了Number的构造函数,因此,可以使用num.constructor==Number来判断一个变量是不是Number类型的。

var num  = 123;
var str  = 'abcdef';
var bool = true;
var arr  = [1, 2, 3, 4];
var json = {name:'wenzi', age:25};
var func = function(){ console.log('this is function'); }
var und  = undefined;
var nul  = null;
var date = new Date();
var reg  = /^[a-zA-Z]{5,20}$/;
var error= new Error();

function Person(){
  
}
var tom = new Person();

// undefined和null没有constructor属性
console.log(
    tom.constructor==Person,
    num.constructor==Number,
    str.constructor==String,
    bool.constructor==Boolean,
    arr.constructor==Array,
    json.constructor==Object,
    func.constructor==Function,
    date.constructor==Date,
    reg.constructor==RegExp,
    error.constructor==Error
);
//所有结果均为true

除了undefined和null之外,其他类型都可以通过constructor属性来判断类型。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值