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

var a = {};

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


当前回答

这一行代码也有助于回退到较旧的浏览器。

var a = {}; //if empty returns false
(Object.getOwnPropertyNames ? Object.getOwnPropertyNames(a).length !== 0 : (function(){ for(var key in a) break; return !!key })()) //Returns False

var a = {b:2}; //if not empty returns true
(Object.getOwnPropertyNames ? Object.getOwnPropertyNames(a).length !== 0 : (function(){ for(var key in a) break; return !!key })()) //Returns true

Object.getOwnPropertyNames在ECMA-5中实现。上面的行在具有回退功能的旧浏览器中工作。


另一个快速解决方案是检查Object.keys、Object.entries或Object.values

知识文章:关注这篇SO文章,了解Object.keys与Object.getOwnPropertyNames之间的详细区别

其他回答

您可以使用Undercore.js。

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

要真正接受ONLY{},在Javascript中使用Lodash的最佳方法是:

_.isEmpty(value) && _.isPlainObject(value)

我在用这个。

function isObjectEmpty(object) {
  var isEmpty = true;
  for (keys in object) {
     isEmpty = false;
     break; // exiting since we found that the object is not empty
  }
  return isEmpty;
}

Eg:

var myObject = {}; // Object is empty
var isEmpty  = isObjectEmpty(myObject); // will return true;
 
// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"}; 
 
// check if the object is empty
isEmpty  = isObjectEmpty(myObject); // will return false;

从这里开始

使现代化

OR

可以使用isEmptyObject的jQuery实现

function isEmptyObject(obj) {
  var name;
  for (name in obj) {
    return false;
  }
  return true;
}

警告当心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

    {}