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

var a = {};

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


当前回答

老问题,但只是有问题。如果您的唯一目的是检查对象是否为空,那么包含JQuery并不是一个好主意。相反,只需深入JQuery的代码,就会得到答案:

function isEmptyObject(obj) {
    var name;
    for (name in obj) {
        if (obj.hasOwnProperty(name)) {
            return false;
        }
    }
    return true;
}

其他回答

我在用这个。

function isObjectEmpty(object) {
  var isEmpty = true;
  for (keys in object) {
     isEmpty = false;
     break; // exiting since we found that the object is not empty
  }
  return isEmpty;
}

Eg:

var myObject = {}; // Object is empty
var isEmpty  = isObjectEmpty(myObject); // will return true;
 
// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"}; 
 
// check if the object is empty
isEmpty  = isObjectEmpty(myObject); // will return false;

从这里开始

使现代化

OR

可以使用isEmptyObject的jQuery实现

function isEmptyObject(obj) {
  var name;
  for (name in obj) {
    return false;
  }
  return true;
}

这与在lodash源中检查对象的方式类似:

const isEmpty = value => {
  for (const key in value) {
    if (hasOwnProperty.call(value, key)) {
      return false
    }
  }
  return true;
}

但有很多其他方法可以做到这一点。

任何类型的值都为空

/* 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,然后总是检查if(!isEmption(obj))之类的否定,你可以只测试对象是否为null,是否有财产

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

Sugar.JS为此提供了扩展对象。代码简洁明了:

创建扩展对象:

a = Object.extended({})

检查尺寸:

a.size()