javascript – 对象是空的吗?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 对象是空的吗?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1543字,纯文字阅读大概需要3分钟。
内容图文
![javascript – 对象是空的吗?](/upload/InfoBanner/zyjiaocheng/717/48ec4b9ec9a04e8e91b77e3bf901eb79.jpg)
参见英文答案 > How do I test for an empty JavaScript object? 44个
检查对象是否为空的最快方法是什么?
有没有比这更快更好的方法:
function count_obj(obj){
var i = 0;
for(var key in obj){
++i;
}
return i;
}
解决方法:
我假设你的意思是“没有自己的属性”.
// 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 browsers,则可以使用Object.getOwnPropertyNames而不是hasOwnProperty循环:
if (Object.getOwnPropertyNames(obj).length > 0) return false;
这将确保即使对象只具有非可枚举属性,isEmpty仍会为您提供正确的结果.
内容总结
以上是互联网集市为您收集整理的javascript – 对象是空的吗?全部内容,希望文章能够帮你解决javascript – 对象是空的吗?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。