如何判断一个对象是否为空
1、利用 Object.keys
方法 该方法会返回当前对象内所有返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable
)属性的键名。详情 Object.keys
;
如果数组的长度不为空那么则说明对象不为空
使用方法如下:
const obj = { name: '张三', age: 18, sex: '男' };
let arr = Object.keys(obj); // ['name', 'age', 'sex']
if(arr.length){
return false;
} else {
return true;
}
抽成方法:
function checkObj(obj){
if (typeof obj != 'object') thorw new Error('参数不是一个可遍历对象');
let _arr = Object.keys(obj);
return !!_arr.length;
}
var obj = {};
checkObj(obj) // false
obj = { name: '张三' }
checkObj(obj) // true
obj = [];
checkObj(obj) // false
obj = [1];
checkObj(obj); // true
obj = function(){};
checkObj(obj) // Uncaught Error: 参数不是可遍历对象;
2、使用for...in
循环,如果对象可循环那么不为空,否则为空对象 ;前提:对象属性是可遍历:
function checkObj(obj){
for(let item in obj){
return true;
}
return false;
}
var obj = {};
checkObj(obj) // false
obj = {name:'张三'}
checkObj(obj);
obj = [];
checkObj(obj);
obj = [1];
checkObj(obj);
obj = function(){}
checkObj(obj) // false