在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
当前回答
警告当心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 {}
其他回答
检查值的新方法是if(Object.entries(this.props.myarticle).length==0){}
这里肌肉是物体
尝试解构
const a = {};
const { b } = a;
const emptryOrNot = (b) ? 'not Empty' : 'empty';
console.log(emptryOrNot)
正确答案是:
function isEmptyObject(obj) {
return (
Object.getPrototypeOf(obj) === Object.prototype &&
Object.getOwnPropertyNames(obj).length === 0 &&
Object.getOwnPropertySymbols(obj).length === 0
);
}
这将检查:
对象的原型完全是object.prototype。该对象没有自己的财产(无论可枚举性如何)。对象没有自己的属性符号。
换句话说,该对象与使用{}创建的对象无法区分。
我的看法:
函数isEmpty(obj){return Object.keys(obj).length==0;}变量a={a: 1中,b: 2个}变量b={}console.log(isEmpty(a));//假的console.log(isEmpty(b));//真的
只是,我认为目前并不是所有浏览器都实现Object.keys()。
我在用这个。
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;
}