判断变量类型

240 阅读2分钟
  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)



未完待续.....