在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
当前回答
您可以在使用对象原型之前或代码开始时定义自己的对象原型。
定义应如下所示:
Object.prototype.hasOwnProperties=函数(){ for(此处为var k){ 如果(this.hasOwnProperty(k)){ 返回true;} }return false;}
下面是一个用法示例:
变量a={};while(a.status!==“完成”){ if(状态==“正在处理”){a.status=“完成”;}if(状态==“启动”){a.status=“正在处理”;}如果(!a.hasOwnProperties()){a.status=“正在启动”;}}
享受!:-)
其他回答
警告当心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 {}
对于有相同问题但使用jQuery的人,可以使用jQuery.isEmptyObject。
这与在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;
}
};
我在用这个。
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;
}