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

var a = {};

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


当前回答

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

其他回答

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

jQuery.isPlainObject({}) // true

jQuery.isPlainObject( "test" ) // false

Jquery api

尝试解构

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/

if(Object.getOwnPropertyNames(obj).length === 0){
  //is empty
}

看见http://bencollier.net/2011/04/javascript-is-an-object-empty/

任何类型的值都为空

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