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

var a = {};

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


当前回答

这里有一个快速、简单的函数:

function isEmptyFunction () {
  for (const i in this) return false
  return true
}

作为getter实现:

Object.defineProperty(Object.prototype, 'isEmpty', { get: isEmptyFunction })

console.log({}.isEmpty) // true

作为单独的功能实现:

const isEmpty = Function.prototype.call.bind(isEmptyFunction)

console.log(isEmpty({})) // true

其他回答

    let jsObject = JSON.parse(JSON.stringify(obj), (key, value) => {
                if (value === null ||
                    value === '' ||
                    (value.constructor === Object && Object.entries(value).length === 0) ||
                    (value.constructor === Array && value.length === 0)) {
                    return undefined
                }
                return value
            })

这将递归地过滤掉所有无效字段。

如果ECMAScript 5支持可用,则可以使用Object.keys():

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}

对于ES3和更高版本,没有简单的方法可以做到这一点。您必须显式循环财产:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

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

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

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

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

    {}