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

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

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

    return i;
}

当前回答

情况有多糟?

function(obj){
    for(var key in obj){
        return false; // not empty
    }

    return true; // empty
}

其他回答

不需要图书馆。

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(obj){
    for(var key in obj){
        return false; // not empty
    }

    return true; // empty
}

假设你有以下对象:

var obj1= {};
var obj2= {test: "test"};

不要忘记我们不能使用===符号来测试对象是否相等,因为他们得到继承,所以如果你使用ECMA 5和更高版本的javascript,答案很简单,你可以使用下面的函数:

function isEmpty(obj) {
   //check if it's an Obj first
   var isObj = obj !== null 
   && typeof obj === 'object' 
   && Object.prototype.toString.call(obj) === '[object Object]';

   if (isObj) {
       for (var o in obj) {
           if (obj.hasOwnProperty(o)) {
               return false;
               break;
           }
       }
       return true;
   } else {
       console.error("isEmpty function only accept an Object");
   }
}

结果如下:

isEmpty(obj1); //this returns true
isEmpty(obj2); //this returns false
isEmpty([]); // log in console: isEmpty function only accept an Object
if (Object.getOwnPropertyNames(obj1).length > 0)
{
 alert('obj1 is empty!');
}

你可以写一个回退数组。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;
}