js如何判断一个对象没有任何自己的属性(为空)?
参考原文
假如有两个空对象, 判断他们是否相等, 结果一定是false:
var a = {}
var b = {}
a == b // false
因为跟c语言类似, 这儿判断的是地址而不是内容.
那么怎么知道a是空呢?
有三个方法. 这儿先假设有一个对象obj
var obj = {}
方法1
Object.keys(obj).length === 0
方法2
Object.getOwnPropertyNames(obj).length === 0
方法3, 自己判断
// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isEmpty(obj) {
// null and undefined are "empty"
if (obj == null) return true;
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// If it isn't an object at this point
// it is empty, but it can't be anything *but* empty
// Is it empty? Depends on your application.
if (typeof obj !== "object") return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
// test it
isEmpty(""), // true
isEmpty(33), // true (arguably could be a TypeError)
isEmpty([]), // true
isEmpty({}), // true
isEmpty({length: 0, custom_property: []}), // true
isEmpty("Hello"), // false
isEmpty([1,2,3]), // false
isEmpty({test: 1}), // false
isEmpty({length: 3, custom_property: [1,2,3]}) // false