判断变量类型

本文介绍JavaScript中使用Object.prototype.toString.call()方法进行精确类型检测的方法,包括基本类型、引用类型及自定义类型的判断,并对比typeof、instanceof和constructor的用法。
  1. object.prototype.toString.call(value) 

    使用Object.prototype上的原生toString()方法判断数据类型,使用方法如下:

    Object.prototype.toString.call(value)

    1.判断基本类型:

    Object.prototype.toString.call(null);//"[object Null]"
    Object.prototype.toString.call(undefined);//"[object Undefined]"
    Object.prototype.toString.call(“abc”);//"[object String]"
    Object.prototype.toString.call(123);//"[object Number]"
    Object.prototype.toString.call(true);//"[object Boolean]"复制代码

    2.判断原生引用类型:

    函数类型
    Function fn(){console.log(“test”);}
    Object.prototype.toString.call(fn);//"[object Function]"复制代码
    日期类型
    var date = new Date();
    Object.prototype.toString.call(date);//"[object Date]"复制代码
    数组类型
    var arr = [1,2,3];
    Object.prototype.toString.call(arr);//"[object Array]"复制代码
    正则表达式
    var reg = /[hbc]at/gi;
    Object.prototype.toString.call(reg);//"[object RegExp]"复制代码
    自定义类型
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    var person = new Person("Rose", 18);
    Object.prototype.toString.call(person); //"[object Object]"复制代码
    很明显这种方法不能准确判断person是Person类的实例,而只能用instanceof 操作符来进行判断,如下所示:
    console.log(person instanceof Person);//输出结果为true复制代码

    3.判断原生JSON对象:

    var isNativeJSON = window.JSON && Object.prototype.toString.call(JSON);
    console.log(isNativeJSON);//输出结果为"[object JSON]"说明JSON是原生的,否则不是;复制代码

    注意:Object.prototype.toString()本身是允许被修改的,而我们目前所讨论的关于Object.prototype.toString()这个方法的应用都是假设toString()方法未被修改为前提的。

  2. typeof
    typeof通常用来判断基本数据类型。当判断对象,数组和null时都返回object.
  3. typeof 'asd'
    =>"string"
    
    typeof 123
    =>"number"
    
    typeof true
    =>"boolean"
    
    typeof undefined
    =>"undefined"
    
    typeof NaN
    =>"number"
    
    typeof null
    =>"object"
    
    typeof [1,2,3]
    =>"object"
    
    typeof {a: '1'}
    =>"object"
    
    function a(){}
    typeof a
    =>"function"
    复制代码

3.instanceof

instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性,意思就是该变量通过原型链上能否找到构造函数的prototype 属性

var arr = [1,2,3]
var obj = {a: '1'}

arr instanceof Array              =>true
arr instanceof Object             =>true        //数组也是对象
obj instanceof Object             =>true复制代码

4.constructor

var arr1 = [1,2,3]
var obj={a: '1'}
var s = '123'
var n = 123

arr1.constructor==Array
=>true

arr1.constructor==Object
=>false

obj.constructor==Object
=>true

s.constructor==String
=>true

n.constructor==Number
=>true

true.constructor==Boolean
=>true复制代码

总结:判断基本类型我会用typeof,判断引用类型我会用instanceof,更推荐用Object.prototype.toString.call(value)



未完待续.....


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值