本文共 1694 字,大约阅读时间需要 5 分钟。
本文翻译自:
What is the fastest way to check if an object is empty or not? 检查对象是否为空的最快方法是什么?
Is there a faster and better way than this: 有没有比这更快更好的方法:
function count_obj(obj){ var i = 0; for(var key in obj){ ++i; } return i;}
参考:
EDIT : Note that you should probably use instead of this since ES5 support is these days. 编辑 :请注意,您可能应该使用而不是使用此 ,因为近来对ES5的支持非常 。 It still works for jQuery though. 它仍然适用于jQuery。
Easy and cross-browser way is by using jQuery.isEmptyObject
: 简单而跨浏览器的方法是使用jQuery.isEmptyObject
:
if ($.isEmptyObject(obj)){ // do something}
More: 更多: :
You need jquery though. 你需要jQuery。
No need for a library. 无需图书馆。
function(){ //must be within a function var obj = {}; //the object to test for(var isNotEmpty in obj) //will loop through once if there is a property of some sort, then return alert('not empty')//what ever you are trying to do once return alert('empty'); //nope obj was empty do this instead;}
if (Object.getOwnPropertyNames(obj1).length > 0){ alert('obj1 is empty!');}
快速在线搜索“字典”对象:
function isEmptyDict(d){for (var k in d) return false; return true}
You can write a fallback if Array.isArray and Object.getOwnPropertyNames is not available 如果Array.isArray和Object.getOwnPropertyNames不可用,则可以编写后备
XX.isEmpty = function(a){ if(Array.isArray(a)){ return (a.length==0); } if(!a){ return true; } if(a instanceof Object){ if(a instanceof Date){ return false; } if(Object.getOwnPropertyNames(a).length == 0){ return true; } } return false;}
转载地址:http://cpcnb.baihongyu.com/