JavaScript检测数据类型及模仿jQuery中的数据类型检测

JavaScript检测数据类型

  • 共四种检测方法
  1. typeof

    用来检测数据类型的运算符

    适合 string number undefined boolean function

    typeof val 返回字符串
    "helo"-> "string"
    1->"number"
    false -> "boolean"
    function(){} -> "function"
    undefined -> "undefined"
    null -> "object"
    symbol -> "symbol"
    
    //无法真正的区分引用数据类型
    {} -> "object"
    [] -> "object"
    /^[ab]/ -> "object"
    

    局限性: typeof null -> "object" 将null当做空对象指针,

    typeof [] -> "object" 无法区分对象的具体类型(无法区分正则,数组,普通对象或者null)

    优势:足够快!!!简单!!对于基本数据类型适合用于检测, number , string , boolean , undefined,symbol 函数(function)

    • undefined == null // true

    • undefined === null // false

    • 应用:形参赋值为默认值

      function func(n,m,callback) {
       // 参数处理:如果参数没有被赋值就会是undefined
        // es6 func(m = 0, n = 0)
        // 1. 监测是否为undefined
        // n === undefined ? n = 0 : null;
        // typeof n === 'undefined' ? n = 0: null
      
        // 逻辑或表达式 缺陷是:当n = false的时候也是设置为 0 
        n = n || 0;
        m = m || 0;
      

      typeof callback === 'function' ? null: callback();
      callback && callback(); // 缺陷就是: callback =转为boolean为 true的时候,也会当做函数来执行
      }

      
      
      
  2. instanceof 运算符

    本意:检测数据是否隶属于某个类

    缺点:

    i. 不能用于检测基本数据类型值

    ii. 只要在当前实例中原型链__proto__中出现过的类检测结果都是true;

    ii. 用户手动修改原型链指向

    let arr = [],
    reg = /^$/;
    arr instanceof Array // true
    reg instanceof Array // false
    
    arr instanceof Object // true 对应ii
    
    1 instanceof Number // false
    let one = new Number(1);
    one instanceof Number
    
  3. constructor

    在类的原型上一般会有 constructor 存储当前类的指针

    缺点:如果修改了constructor 会导致结果不符合预期: 重构prototype或者添加私有属性添加constructor

    null 和 undefined没有constructor

    let n = 12,
        arr = [];
    arr.constructor == Array // true;
    n.constructor == Number
    
    
    arr.constructor = 11;
    
    
  4. Object.prototype.toString.call(value) 改变方法中的this,待检测的数据类型 "[object xxx]"

    原理: 在Array, RegExp,Function中的prototype存在toString方法,将他们转为字符串

    而在Object中的方法toString可以用来检测数据类型的,检测类

    Object.prototype.toString.call([]); // '[object Array]'
    console.log([1,2].toString()); // => 1,2
    console.log(/^123$/.toString()); // => /^123$/
    console.log((function(){}).toString()); // function(){}
    
    let getType = (arg)=>Object.prototype.toString.call(arg);
    getType(/adsf/);
    '[object RegExp]'
    > getType(new Date());
    '[object Date]'
    > getType(true);
    '[object Boolean]'
    > getType(null);
    '[object Null]'
    > getType(undefined);
    '[object Undefined]'
    >
    

自己封装

    let _obj = {
            isNull: "Null",
            isUndefined: "Undefiend",
            isString: "String",
            isNumberic: "Number",
            isFunction: "Function",
            isBoolean: "Boolean",
            isWindow: "Window",
            isPlainObject: "Object",
            isArray: "Array",
            isRegExp: "RegExp",
            isDate: "Date",
            isSymbol: "Symbol"

        },
        _toString = _obj.toString,
        _type = {};
    for (let key in _obj) {
      	// 构造匹配规则
        let msg = `\[object ${_obj[key]}\]`;
        let reg = new RegExp(msg);
      // 过滤原型上的属性
        if (!_obj.hasOwnProperty(key)) break;
        _type[key] = function(val) {
            return reg.test(_toString.call(val));
        }
    }
慢慢来,比较快!基础要牢,根基要稳!向大佬致敬!
原文地址:https://www.cnblogs.com/rookie123/p/14473239.html