判断js的数据类型,如:Boolean Number String等
javascript获取数据类型
平时在工作中,偶尔会用到判断一下这个数据是什么类型,是数组的?string的?function的?我一般都直接按照代码的需求,只写了需要判断的类型,用完就丢到一边,最近在看jquery源码,人家大牛写的真不错,改一改,封装一下,自己用哈。
话不多说,直接贴出代码,其实很简单的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function toType( obj ) { var class2type = {}, toString = class2type.toString;
"Boolean Number String Function Array Date RegExp Object Error Symbol" .split( " " ) .forEach(function( name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); });
if ( obj == null ) { return obj + ""; }
return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; }
|
代码一共没有几行,接下来看看管不管用
1 2 3 4 5 6 7 8 9 10 11 12 13
| console.log('对象的类型->',toType({})); console.log('函数的类型->',toType(function(){})); console.log('null的类型->',toType(null)); console.log('undefined的类型->',toType(undefined)); console.log('boolean的类型->',toType(true)); console.log('number的类型->',toType(555)); console.log('string的类型->',toType('abc')); console.log('array的类型->',toType([])); console.log('date的类型->',toType(new Date())); console.log('正则的类型->',toType(/abc/g)); console.log('symbol->',toType(Symbol())); console.log('Error的类型->',toType(new Error()));
|
基本上的类型都判断出来了,不错吧。