在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:

var a = {};

我该如何检查是否是这种情况?


当前回答

正确答案是:

function isEmptyObject(obj) {
  return (
    Object.getPrototypeOf(obj) === Object.prototype &&
    Object.getOwnPropertyNames(obj).length === 0 &&
    Object.getOwnPropertySymbols(obj).length === 0
  );
}

这将检查:

对象的原型完全是object.prototype。该对象没有自己的财产(无论可枚举性如何)。对象没有自己的属性符号。

换句话说,该对象与使用{}创建的对象无法区分。

其他回答

您可以使用Undercore.js。

_.isEmpty({}); // true

如果您使用更新的浏览器,有一个简单的方法。对象.keys(obj).length==0

我能找到的最佳单线解决方案(已更新):

isEmpty=obj=>!Object.values(obj).filter(e=>类型e!=='undefined').length;console.log(isEmpty({}))//trueconsole.log(isEmpty({a:undefined,b:undefine}))//trueconsole.log(isEmpty({a:undefined,b:void 1024,c:void 0}))//trueconsole.log(isEmpty({a:[undefined,undefined]}))//falseconsole.log(isEmpty({a:1}))//falseconsole.log(isEmpty({a:“”}))//falseconsole.log(isEmpty({a:null,b:undefined}))//false

警告当心JSON的限制。

javascript:
  obj={  f:function(){}  };
  alert( "Beware!! obj is NOT empty!\n\nobj = {  f:function(){}  }" + 
               "\n\nJSON.stringify( obj )\n\nreturns\n\n" +
                        JSON.stringify( obj ) );

显示器

    Beware!! obj is NOT empty!

    obj = {  f:function(){}  }

    JSON.stringify( obj )

    returns

    {}
function isEmpty(obj) {
  for(var i in obj) { return false; }
  return true;
}