JS判断数据类型

 var testArr = [
        1,
        "1",
        {},
        [1,2],
        null,
        undefined
];
function getType(obj){
        let type  = typeof obj;
        if (type !== "object") {    // 先进行typeof判断,如果是基础数据类型,直接返回
            return type;
        }
        // 对于typeof返回结果是object的,再进行如下的判断,正则返回结果
        return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1');  
};
testArr.map(i=>{
        console.log(getType(i))
});
image.png
Object.prototype.toString.call(),可以很好地判断引用类型,
甚至可以把 document 和 window 都区分开来,
使用这个方法最后返回统一字符串格式为 "[object Xxx]"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。