检查对象是否为空的最快方法是什么?
有没有比这更快更好的方法:
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;
}
当前回答
编辑:请注意,您可能应该使用ES5解决方案而不是这个,因为ES5支持现在已经广泛使用。但它仍然适用于jQuery。
简单和跨浏览器的方法是使用jQuery.isEmptyObject:
if ($.isEmptyObject(obj))
{
// do something
}
更多:http://api.jquery.com/jQuery.isEmptyObject/
但是你需要jquery。
其他回答
很惊讶在这么一个基本的JS问题上看到这么多弱的答案…上面的答案也不好,原因如下:
它生成一个全局变量 在未定义时返回true 用途……它本身非常慢 函数内部为…在是无用的-返回false没有hasOwnProperty魔法将工作良好
事实上,有一个更简单的解决方案:
function isEmpty(value) {
return Boolean(value && typeof value === 'object') && !Object.keys(value).length;
}
这是我的解决方案
function isEmpty(value) {
if(Object.prototype.toString.call(value) === '[object Array]') {
return value.length == 0;
} else if(value != null && typeof value === 'object') {
return Object.getOwnPropertyNames(value).length == 0;
} else {
return !(value || (value === 0));
}
}
解围球
你可以写一个回退数组。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;
}
不需要图书馆。
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;
}
function isEmpty( o ) {
for ( var p in o ) {
if ( o.hasOwnProperty( p ) ) { return false; }
}
return true;
}