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

var a = {};

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


当前回答

完美的故障保护解决方案

我认为第一个被接受的解决方案在大多数情况下都有效,但不是故障保护。

更好的故障安全解决方案将是。

function isEmptyObject() { 
  return toString.call(obj) === "[object Object]" 
  && Object.keys(obj).length === 0;
}

或ES6/7

const isEmptyObject = () => toString.call(obj) === "[object Object]" 
  && Object.keys(obj).length === 0;

使用这种方法,如果obj设置为undefined或null,则代码不会中断。并返回null。

其他回答

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

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

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

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

您可以使用Undercore.js。

_.isEmpty({}); // true

对于有相同问题但使用jQuery的人,可以使用jQuery.isEmptyObject。