JavaScript判断值为对象或数组的方法

实际项目应用中,我们会经常遇到判断数据类型的情况,以下为大家列出几种判断方法:

1. typeof 

console.log(typeof '123')   //"string"

console.log(typeof 123)   //"number"

console.log(typeof true)   //"boolean"

console.log(typeof {})   //"object"

console.log(typeof [])   //"object"

console.log(typeof null)   //"object"

console.log(typeof undefined)   //"undefined"

console.log(typeof function(){})   //"function"

2. instanceof   

检测函数的prototype是否在被检测对象的原型链上,如下,所以我们在检测所需数据类型只能是对象时,会存在错误

console.log([] instanceof Object, [] instanceof Array)   //true,true  Array.prototype.__proto__ === Object.prototype

console.log({} instanceof Object)   //true

console.log((()=>{}) instanceof Function) // true  Function.prototype.__proto__ === Object.prototype

console.log((()=>{}) instanceof Object) // true

3. 判断数组常用方法

console.log(Array.isArray([]))   //true

console.log([] instanceof Array)   //true

console.log([].constructor === Array)   //true

console.log(Object.prototype.toString.call([]) === '[object Array]')   //true

4. 判断对象常用方法

console.log(Object.prototype.toString.call({}) === '[object Object]')   //true

console.log({}.constructor === Object)   //true

console.log(obj instanceof Object) //true  除对象类型,数组函数判断也为true

console.log(typeof {} === "object") //true 除对象类型,数组函数及null判断也为true

在日常使用中除了判断数据类型外,还常会判断是否为空数组空对象,以下我列出了几种常用的方法:

1. 判断数组不为空

console.log( [] && [].length>0 )   //false

console.log(JSON.stringify([])!=="[]")   //false

2. 判断对象不为空

console.log(Object.getOwnPropertyNames({}).length>0)   //false

console.log(Object.keys({}).length>0)   //false

console.log(JSON.stringify({})!=='{}')   //false

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值