在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
当前回答
这里有一个快速、简单的函数:
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
其他回答
let jsObject = JSON.parse(JSON.stringify(obj), (key, value) => {
if (value === null ||
value === '' ||
(value.constructor === Object && Object.entries(value).length === 0) ||
(value.constructor === Array && value.length === 0)) {
return undefined
}
return value
})
这将递归地过滤掉所有无效字段。
老问题,但只是有问题。如果您的唯一目的是检查对象是否为空,那么包含JQuery并不是一个好主意。相反,只需深入JQuery的代码,就会得到答案:
function isEmptyObject(obj) {
var name;
for (name in obj) {
if (obj.hasOwnProperty(name)) {
return false;
}
}
return true;
}
这就是我想到的,用来判断对象中是否有任何非空值。
function isEmpty(obj: Object): Boolean {
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (obj[prop] instanceof Object) {
const rtn = this.isEmpty(obj[prop]);
if (rtn === false) {
return false;
}
} else if (obj[prop] || obj[prop] === false) {
return false;
}
}
}
return true;
}
警告当心JSON的限制。
javascript:
obj={ f:function(){} };
alert( "Beware!! obj is NOT empty!\n\nobj = { f:function(){} }" +
"\n\nJSON.stringify( obj )\n\nreturns\n\n" +
JSON.stringify( obj ) );
显示器
Beware!! obj is NOT empty! obj = { f:function(){} } JSON.stringify( obj ) returns {}
我在用这个。
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;
}