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

var a = {};

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


当前回答

我在用这个。

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

其他回答

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

jQuery.isPlainObject({}) // true

jQuery.isPlainObject( "test" ) // false

Jquery api

我的看法:

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

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

您可以使用Undercore.js。

_.isEmpty({}); // true

除了Thevs的回答:

var o = {};
alert($.toJSON(o)=='{}'); // true

var o = {a:1};
alert($.toJSON(o)=='{}'); // false

它是jquery+jquery.json

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

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