js检测对象类型

2021-02-03  本文已影响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)
}
上一篇下一篇

猜你喜欢

热点阅读