在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
当前回答
jQuery在这种情况下具有特殊的函数isEmptyObject():
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false
阅读更多信息http://api.jquery.com/jQuery.isEmptyObject/
其他回答
我在用这个。
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;
}
如果ECMAScript 5支持可用,则可以使用Object.keys():
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
对于ES3和更高版本,没有简单的方法可以做到这一点。您必须显式循环财产:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
我为AJAX调用返回了一个空的JSON响应,在IE8中jQuery.isEmptyObject()没有正确验证。我加了一张额外的支票,似乎能正确地抓住它。
.done(function(data)
{
// Parse json response object
var response = jQuery.parseJSON(data);
// In IE 8 isEmptyObject doesn't catch the empty response, so adding additional undefined check
if(jQuery.isEmptyObject(response) || response.length === 0)
{
//empty
}
else
{
//not empty
}
});
我能找到的最佳单线解决方案(已更新):
isEmpty=obj=>!Object.values(obj).filter(e=>类型e!=='undefined').length;console.log(isEmpty({}))//trueconsole.log(isEmpty({a:undefined,b:undefine}))//trueconsole.log(isEmpty({a:undefined,b:void 1024,c:void 0}))//trueconsole.log(isEmpty({a:[undefined,undefined]}))//falseconsole.log(isEmpty({a:1}))//falseconsole.log(isEmpty({a:“”}))//falseconsole.log(isEmpty({a:null,b:undefined}))//false
老问题,但只是有问题。如果您的唯一目的是检查对象是否为空,那么包含JQuery并不是一个好主意。相反,只需深入JQuery的代码,就会得到答案:
function isEmptyObject(obj) {
var name;
for (name in obj) {
if (obj.hasOwnProperty(name)) {
return false;
}
}
return true;
}