js判断数组为空或null
作者:互联网
方法:
let value = {} value && Object.keys(value).length === 0 && value.constructor === Object;
原因:
let a = {} let b = new Object() let c = new String(); if(Object.keys(a).length === 0 && a.constructor === Object){ //true console.log('数组为空或null') } if(Object.keys(b).length === 0 && b.constructor === Object){ //true console.log('数组为空或null') } if(Object.keys(c).length === 0 && c.constructor === Object){ //false console.log('数组为空或null') } // 补充:对constructor进行检查,是为了覆盖包装器实例,仅使用Object.keys,当对象为空时,它的确会返回true,但是,当我们使用除new Object()以外的构造函数创建新的对象实例时 if(Object.keys(c).length){ //true console.log('数组为空或null') } //console.log('数组为空或null') //所以,需要对constructor进行检查 function isElementObject (value){ return Object.keys(value).length === 0 && value.constructor === Object; } // 当心,对null和undefined值的判断会引发TypeError错误,例如: console.log(isElementObject(null)) console.log(isElementObject(undefined)) //"TypeError: Cannot convert undefined or null to object" //改进:对null和undefined的空检查,最终: function isElementObject2 (value){ return value && Object.keys(value).length === 0 && value.constructor === Object; } console.log(isElementObject2(null)) console.log(isElementObject2(undefined))
标签:console,log,keys,Object,value,js,为空,null 来源: https://www.cnblogs.com/wang715100018066/p/16457506.html