对象是否为空?
2022-08-29 23:04:20
检查对象是否为空的最快方法是什么?
有没有比这更快更好的方法:
function count_obj(obj){
var i = 0;
for(var key in obj){
++i;
}
return i;
}
检查对象是否为空的最快方法是什么?
有没有比这更快更好的方法:
function count_obj(obj){
var i = 0;
for(var key in obj){
++i;
}
return i;
}
对于 ECMAScript5(但并非所有浏览器都支持),您可以使用:
Object.keys(obj).length === 0
我假设你说的空的意思是“没有自己的属性”。
// 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;
}
例子:
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
如果你只需要处理 ECMAScript5 浏览器,你可以使用 Object.getOwnPropertyNames
而不是 hasOwnProperty
循环:
if (Object.getOwnPropertyNames(obj).length > 0) return false;
这将确保即使对象仅具有不可枚举的属性,仍会为您提供正确的结果。isEmpty