js检测对象类型

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

检测对象是否可迭代
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)
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容