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

var a = {};

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


当前回答

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

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

其他回答

你最想知道的是,在使用对象之前,它是否有财产。因此,不要询问isEmpty,然后总是检查if(!isEmption(obj))之类的否定,你可以只测试对象是否为null,是否有财产

export function hasProperties(obj): boolean {
  return obj && obj.constructor === Object && Object.keys(obj).length >= 1;
}

您可以使用Undercore.js。

_.isEmpty({}); // true

我为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
    }
});

从jQuery 1.4开始,isEmptyObject()方法检查对象本身的财产和从原型继承的财产(因为它不使用hasOwnProperty)。参数应该始终是一个普通的JavaScript对象,因为其他类型的对象(DOM元素、原始字符串/数字、宿主对象)可能不会在浏览器中提供一致的结果。要确定对象是否为纯JavaScript对象,请使用$.isPlainObject()。

jQuery.isPlainObject({}) // true

jQuery.isPlainObject( "test" ) // false

Jquery api

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

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