美文网首页
js检测对象类型

js检测对象类型

作者: 攻城熊 | 来源:发表于2021-02-03 15:45 被阅读0次

    检测对象, 这个是深拷贝的基石

    检测对象是否可迭代
    const isIterator = obj => obj != null && typeof obj[Symbol.iterator]

    js判断字符串是否为JSON格式

    function isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj=JSON.parse(str);
                if(typeof obj == 'object' && obj ){
                    return true;
                }else{
                    return false;
                }
    
            } catch(e) {
                console.log('error:'+str+'!!!'+e);
                return false;
            }
        }
        console.log('It is not a string!')
    }
    
    function formatRequest(str){
           if(isJSON(str)){
               var JSONString = JSON.stringify(JSON.parse(str), null, "\t");
           }else{
               alert("不是正确的JSON格式")
           }
    }
    

    判断数组

    Array.isArray(arr)
    Object.prototype.toString(arr) == [object Object]
    Object.prototype.toString.call(arr) === '[object Array]'
    arr.__proto__  === Array.prototype  // 不安全
    arr  instanceof Array  // 不安全
    arr.constructor === Array  // 不安全
    

    判断对象

    // 工具函数
    let _toString = Object.prototype.toString
    let map = {
      array: 'Array',
      object: 'Object',
      function: 'Function',
      string: 'String',
      null: 'Null',
      undefined: 'Undefined',
      boolean: 'Boolean',
      number: 'Number'
    }
    let getType = (item) => {
      return _toString.call(item).slice(8, -1)
    }
    let isTypeOf = (item, type) => {
      return map[type] && map[type] === getType(item)
    }
    

    相关文章

      网友评论

          本文标题:js检测对象类型

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