检测数据类型的方法

我们在写代码逻辑的时候,有时候需要用到准确的数据类型,尤其是数组(Array)和对象(Object)之类的引用数据类型。所以我整理了一些判断数据类型的方法,希望能对你有所帮助。

typeof

使用方法:直接在变量前加上typeof即可

var arr=[],num=1,obj={},str="string"
console.log(typeof arr)
console.log(typeof num)
console.log(typeof obj)
console.log(typeof str)

在这里插入图片描述
优点:

  • 可以直接返回表示数据类型的字符串(包括number,boolean,string,function,object,undefined)
  • 使用起来方便

缺点:

  • 无法细致的判断Array,无论变量是数组还是对象都返回Object

instanceof

使用方法: A instance B(Array,Object,Number,Boolean,String,Function,Undefined)

var arr=[],num=1,obj={},str="string"
console.log(arr instanceof Array)   //true
console.log(arr instanceof Number)  //true
console.log(arr instanceof Object)  //true

优点:

  • 在某些条件分支时适用

缺点:

  • 和typeof类似,instanceof在数组和对象的问题上有瑕疵,当你使用数组去判断对象时(arr instance Object),返回结果同样是true

使用Object下的toString.call()来判断

使用方法:Object.prototype.toString.call()

console.log(toString.call(123)); //[object Number]
console.log(toString.call('123')); //[object String]
console.log(toString.call(undefined)); //[object Undefined]
console.log(toString.call(true)); //[object Boolean]
console.log(toString.call({})); //[object Object]
console.log(toString.call([])); //[object Array]
console.log(toString.call(function(){})); //[object Function]

优点:

  • 判断极为准确,能够清楚地判断数组和对象

缺点:

  • 它的返回结果是[object 数据类型]这种格式的,如果需要获取数据类型的话可能还需要裁取一下(Object.prototype.toString.call().slice(8,-1))

根据对象的contructor判断

console.log('数据类型判断' -  constructor);
console.log(arr.constructor === Array); //true
console.log(date.constructor === Date); //true
console.log(fn.constructor === Function); //true

jQuery中的判断方法

jQuery提供了一系列工具方法,用来判断数据类型,以弥补JavaScript原生的typeof运算符的不足。以下方法对参数进行判断,返回一个布尔值。
jQuery.isArray();是否为数组
jQuery.isEmptyObject();是否为空对象 (不含可枚举属性)。
jQuery.isFunction():是否为函数
jQuery.isNumberic():是否为数字
jQuery.isPlainObject():是否为使用“{}”或“new Object”生成对象,而不是浏览器原生提供的对象。
jQuery.isWindow(): 是否为window对象;
jQuery.isXMLDoc(): 判断一个DOM节点是否处于XML文档中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值