这篇文章将为大家详细讲解有关使用JS如何实现判断数据类型,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
有五种数据判断类型方法typeof 、instanceof、constructor、Object.prototype.toString.call()、jquery.type()
一、typeof方法
typeof是个操作符,可以判断基本数据类型(返回的结果只能是number,string,boolean,null,symbol,function,object)
返回值分以下几种
对于基本类型。除了null值返回object以外,其他均返回正确的结果
对于引用值来说,除了function返回function类型,其他都返回object类型
例:
console.log( typeof 100, //"number" typeof 'abc', //"string" typeof false, //"boolean" typeof undefined, //"undefined" typeof null, //"object" typeof [1,2,3], //"object" typeof {a:1,b:2,c:3}, //"object" typeof function(){console.log('aaa');}, //"function" typeof new Date(), //"object" typeof /^[a-zA-Z]{5,20}$/, //"object" typeof new Error() //"object" typeof new Number(100), //'object' typeof new String('abc'),// 'string' typeof new Boolean(true),//'boolean' )