在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
在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;
}
其他回答
如果您使用更新的浏览器,有一个简单的方法。对象.keys(obj).length==0
除了Thevs的回答:
var o = {};
alert($.toJSON(o)=='{}'); // true
var o = {a:1};
alert($.toJSON(o)=='{}'); // false
它是jquery+jquery.json
我在用这个。
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;
}
警告当心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 {}
这与在lodash源中检查对象的方式类似:
const isEmpty = value => {
for (const key in value) {
if (hasOwnProperty.call(value, key)) {
return false
}
}
return true;
}
但有很多其他方法可以做到这一点。