美文网首页
JS类型检测

JS类型检测

作者: 凯凯frank | 来源:发表于2020-02-23 22:21 被阅读0次

    es5中有5种基本数据类型(undefined null boolean number string),和1中复杂数据类型(object)。

    typeof

    typeof一般用于基础数据类型的检测
    使用typeof,可以返回的类型:

    ‘undefined’//值未定义
    'boolean'//值是布尔值
    'string' //值是字符串
    'number'//值是数字
    'object'//值是对象或者null
    

    instanceof

    instanceof用来检测对象类型

    function Person(){
    }
    console.log(new Person() instanceof Person)//true
    console.log(new Person() instanceof Object)//true,所有的对象均继承自Object
    

    存在的问题:instanceof操作符在多个全局作用域的情况下(比如一个页面包含多个iframe)时,会存在问题。比如:

    var isArray = value instanceof of Array
    

    value如果和Array不是在同一个全局作用域中,会返回false

    var iframe = document.createElement('iframe');
    document.body.appendChild(iframe);
    xArray = window.frames[window.frames.length-1].Array;
    var arr = new xArray(1,2,3); // [1,2,3]
    
    // Correctly checking for Array
    Array.isArray(arr);  // true
    // Considered harmful, because doesn't work though iframes
    arr instanceof Array; // false
    

    Object.prototype.toString.call

    在任何值上调用Object原生的toString()方法,都会返回[Object NativeConstructorName]格式的字符串。每个类在内部都有一个[[Class]]属性,这个属性就指定了上述字符串中的构造函数名,即(NativeConstructorName)。举个例子:

    arr = [];
    Object.prototype.toString.call(arr) // [object Array]
    

    Object的toString方法只能检测原生构造函数的构造函数名。自定义的构造函数都将返回[object Object]

    function Person(){
    }
    console.log(Object.prototype.toString.call(Person))//[object Function]
    console.log(Object.prototype.toString.call(new Person()))//[object Object]
    

    相关文章

      网友评论

          本文标题:JS类型检测

          本文链接:https://www.haomeiwen.com/subject/wuqeqhtx.html