首页 > Web开发 > 详细

js数据类型判断

时间:2019-09-09 13:07:56      阅读:73      评论:0      收藏:0      [点我收藏+]
判断 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;

}

js数据类型判断

原文:https://www.cnblogs.com/fmixue/p/11490862.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!