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

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

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

    return i;
}

当前回答

我修改了肖恩·维埃拉的代码来满足我的需要。Null和undefined根本不算作对象,数字、布尔值和空字符串返回false。

'use strict'; // Speed up calls to hasOwnProperty var hasOwnProperty = Object.prototype.hasOwnProperty; var isObjectEmpty = function(obj) { // null and undefined are not empty if (obj == null) return false; if(obj === false) return false; if(obj === true) return false; if(obj === "") return false; if(typeof obj === "number") { return false; } // 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; // 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; }; exports.isObjectEmpty = isObjectEmpty;

其他回答

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

对于ECMAScript5(不是所有浏览器都支持),你可以使用:

Object.keys(obj).length === 0

这可能有点俗气。你可以试试这个。

if (JSON.stringify(data).length === 2) {
   // Do something
}

不确定这种方法是否有任何缺点。

很惊讶在这么一个基本的JS问题上看到这么多弱的答案…上面的答案也不好,原因如下:

它生成一个全局变量 在未定义时返回true 用途……它本身非常慢 函数内部为…在是无用的-返回false没有hasOwnProperty魔法将工作良好

事实上,有一个更简单的解决方案:

function isEmpty(value) {
    return Boolean(value && typeof value === 'object') && !Object.keys(value).length;
}
if (Object.getOwnPropertyNames(obj1).length > 0)
{
 alert('obj1 is empty!');
}