判断数据类型
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');
//注意正则中间有个空格
}
getType([]) //"Array"
getType('123') //"string"
getType(null) //"Null"
本文介绍了一个JavaScript函数,用于精确地检测变量的数据类型,包括基础类型和复杂类型如Array、Null等。通过结合typeof操作符和Object.prototype.toString方法实现。

被折叠的 条评论
为什么被折叠?



