检查对象是否为空的最快方法是什么?

有没有比这更快更好的方法:

function count_obj(obj){
    var i = 0;
    for(var key in obj){
        ++i;
    }

    return i;
}

当前回答

这是我的解决方案

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));
    }
}

解围球

其他回答

编辑:请注意,您可能应该使用ES5解决方案而不是这个,因为ES5支持现在已经广泛使用。但它仍然适用于jQuery。


简单和跨浏览器的方法是使用jQuery.isEmptyObject:

if ($.isEmptyObject(obj))
{
    // do something
}

更多:http://api.jquery.com/jQuery.isEmptyObject/

但是你需要jquery。

funtion isEmpty(o,i)
{
    for(i in o)
    {
        return!1
    }
    return!0
}

不需要图书馆。

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!');
}

也许你可以用这个决定:

var isEmpty = function(obj) {
  for (var key in obj)
    if(obj.hasOwnProperty(key))
      return false;
  return true;
}