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

var a = {};

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


当前回答

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

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

其他回答

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

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

这与在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;
  }
};

只是一个变通办法。如果没有数据,服务器是否可以生成一些特殊属性?例如:var a={empty:true};然后,您可以在AJAX回调代码中轻松检查它。另一种检查方法:如果(a.toSource()==“({})”)//则“a”为空

编辑:如果您使用任何JSON库(例如JSON.js),那么可以尝试JSON.encode()函数,并根据空值字符串测试结果。

纯Vanilla Javascript,完全向后兼容

函数isObjectDefined(Obj){如果(对象===null||对象类型!=='对象'||Object.pr原型.toString.call(Obj)==“[对象数组]”){return false}其他{for(对象中的var prop){if(对象hasOwnProperty(prop)){返回true}}返回JSON.stringify(Obj)!==JSON字符串({})}}console.log(isObjectDefined())//falseconsole.log(isObjectDefined(“”))//falseconsole.log(isObjectDefined(1))//falseconsole.log(isObjectDefined('string'))//falseconsole.log(isObjectDefined(NaN))//falseconsole.log(isObjectDefined(null))//falseconsole.log(isObjectDefined({}))//falseconsole.log(isObjectDefined([]))//falseconsole.log(isObjectDefined({a:“”}))//true