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

var a = {};

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


当前回答

任何类型的值都为空

/* eslint-disable no-nested-ternary */

const isEmpty = value => {
  switch (typeof value) {
    case 'undefined':
      return true;
    case 'object':
      return value === null
        ? true
        : Array.isArray(value)
        ? !value.length
        : Object.entries(value).length === 0 && value.constructor === Object;
    case 'string':
      return !value.length;
    default:
      return false;
  }
};

其他回答

我的看法:

函数isEmpty(obj){return Object.keys(obj).length==0;}变量a={a: 1中,b: 2个}变量b={}console.log(isEmpty(a));//假的console.log(isEmpty(b));//真的

只是,我认为目前并不是所有浏览器都实现Object.keys()。

如果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
    }
});

尝试解构

const a = {};
const { b } = a;
const emptryOrNot = (b) ? 'not Empty' : 'empty';
console.log(emptryOrNot)

jQuery在这种情况下具有特殊的函数isEmptyObject():

jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false

阅读更多信息http://api.jquery.com/jQuery.isEmptyObject/