判断 Target 的类型,单单用 typeof 并无法完全满足,因此要真正完美判断时,我们需要区分对待:

1、基本类型(null): 使用String(null) ;

2、基本类型(string / number / boolean / undefined)+ function: 直接使用typeof即可 ;

3、(Array / Date / RegExp Error): 调用toString后根据 [object xxx] 进行判断;

比较全面的判断封装:

let class2type = {};

'Array Date RegExp Object Error'.split(' ').forEach(e => class2type[ '[object ' + e + ']' ] = e.toLowerCase()) ;

function type(obj) {

if (obj == null) return String(obj);

return typeof obj === 'object' ? class2type[ Object.prototype.toString.call(obj) ] || 'object' : typeof obj;

}