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

var a = {};

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


当前回答

我为AJAX调用返回了一个空的JSON响应,在IE8中jQuery.isEmptyObject()没有正确验证。我加了一张额外的支票,似乎能正确地抓住它。

.done(function(data)
{  
    // Parse json response object
    var response = jQuery.parseJSON(data);

    // In IE 8 isEmptyObject doesn't catch the empty response, so adding additional undefined check
    if(jQuery.isEmptyObject(response) || response.length === 0)
    {
        //empty
    }
    else
    {
        //not empty
    }
});

其他回答

纯Vanilla Javascript,完全向后兼容

函数isObjectDefined(Obj){如果(对象===null||对象类型!=='对象'||Object.pr原型.toString.call(Obj)==“[对象数组]”){return false}其他{for(对象中的var prop){if(对象hasOwnProperty(prop)){返回true}}返回JSON.stringify(Obj)!==JSON字符串({})}}console.log(isObjectDefined())//falseconsole.log(isObjectDefined(“”))//falseconsole.log(isObjectDefined(1))//falseconsole.log(isObjectDefined('string'))//falseconsole.log(isObjectDefined(NaN))//falseconsole.log(isObjectDefined(null))//falseconsole.log(isObjectDefined({}))//falseconsole.log(isObjectDefined([]))//falseconsole.log(isObjectDefined({a:“”}))//true

表演

今天2020.01.17,我在Chrome v79.0、Safari v13.0.4和Firefox v72.0上对macOS High Sierra 10.13.6进行了测试;对于所选的解决方案。

结论

基于for in(A,J,L,M)的解决方案最快基于JSON.stringify(B,K)的解决方案很慢令人惊讶的是,基于Object(N)的解决方案也很慢注意:此表与下面的照片不匹配。

细节

下面的代码片段中提供了15种解决方案。如果您想在机器上运行性能测试,请单击此处。该链接于2021.07.08年更新,但最初在这里进行测试,上表中的结果来自那里(但现在看起来该服务不再工作)。

var log=(s,f)=>console.log(`${s}-->{}:${f({})}{k:2}:${f({k:2})}`);函数A(obj){for(obj中的var i)返回false;返回true;}函数B(obj){返回JSON.stringify(obj)==“{}”;}函数C(obj){return Object.keys(obj).length==0;}函数D(obj){return Object.entries(obj).length==0;}函数E(obj){return Object.getOwnPropertyNames(obj).length==0;}函数F(obj){return Object.keys(obj).length==0&&obj.constructor==对象;}函数G(obj){返回obj类型==“undefined”||!布尔(Object.keys(obj)[0]);}函数H(obj){return Object.entries(obj).length==0&&obj.constructor==对象;}函数I(obj){return Object.values(obj).every((val)==>typeof val==“undefined”);}函数J(obj){for(obj中的常量键){if(hasOwnProperty.call(obj,key)){return false;}}返回true;}函数K(obj){for(obj中的var属性){if(obj.hasOwnProperty(prop)){return false;}}返回JSON.stringify(obj)==JSON.sstringify({});}函数L(obj){for(obj中的var属性){if(obj.hasOwnProperty(prop))返回false;}返回true;}函数M(obj){for(obj中的var k){如果(obj.hasOwnProperty(k)){return false;}}返回true;}函数N(obj){返回(对象.getOwnPropertyNames(obj).length==0&&对象.getOwnPropertySymbol(obj).length==0&&Object.getPrototypeOf(obj)==Object.prototype);}函数O(obj){回来(Object.getOwnPropertyNames!==未定义? Object.getOwnPropertyNames(obj).length!==0:(函数(){for(obj中的var键)break;返回键!==空键!==未定义;})());}日志(“A”,A);日志(“B”,B);日志(“C”,C);日志(“D”,D);日志(“E”,E);日志(“F”,F);日志(“G”,G);日志(“H”,H);日志(“I”,I);日志(“J”,J);log(“K”,K);日志(“L”,L);日志(“M”,M);日志(“N”,N);日志(“O”,O);

我在用这个。

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

下面的示例显示了如何测试JavaScript对象是否为空,如果我们所说的空是指它没有自己的财产。

该脚本适用于ES6。

常量isEmpty=(obj)=>{如果(obj===空||obj==未定义||Array.isArray(obj)||对象类型!=='对象') {返回true;}return Object.getOwnPropertyNames(obj).length==0;};console.clear();console.log('---');console.log(isEmpty(“”));//真的console.log(isEmpty(33));//真的console.log(isEmpty([]));//真的console.log(isEmpty({}));//真的console.log(isEmpty({length:0,custom_property:[]}));//假的console.log('---');console.log(isEmpty('Hello'));//真的console.log(isEmpty([1,2,3]));//真的console.log(isEmpty({test:1}));//假的console.log(isEmpty({长度:3,自定义属性:[1,2,3]}));//假的console.log('---');console.log(isEmpty(new Date()));//真的console.log(isEmpty(无限));//真的console.log(isEmpty(null));//真的console.log(isEmpty(未定义));//真的

正确答案是:

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

这将检查:

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

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