js 判断对象是否是空对象

  1. 转换为字符串比较
JSON.stringify(obj) === '{}'

2.for循环比较

var IsEmpty = true

for(var i in obj){
  IsEmpty = false
}

3.Object.getOwnPropertyNames

Object.getOwnPropertyNames(obj).length === 0

4.Object.keys

Object.keys(obj).length === 0

Object.getOwnPropertyNames返回的是对象所有自己的属性,而Object.keys(obj)则返回的是所有可枚举属性

const obj = {};
Object.defineProperties(obj, {
    property1: {enumerable: true, value: 1},
    property2: {enumerable: false, value: 2},
});

console.log(Object.keys(obj));
console.log(Object.getOwnPropertyNames(obj));

["property1"]
["property1", "property2"]

你可能感兴趣的:(js 判断对象是否是空对象)