简体   繁体   English

如何检查对象是否为空? [javascript]

[英]How to check if an object is empty? [javascript]

I need to evaluate if an object is empty.我需要评估一个对象是否为空。

For example suppose I have an object:例如假设我有一个对象:

var home = ....;     // this is an object and after I print it

console.log(home)    // the result of this option is []

//now I need to check if a object is empty or null
if( home == null || home == undefined )
{
    // I don't know specify how object is empty
}

How can I detect whether or not the above object home is null/empty?如何检测上述对象home是否为空/空?

To check for an empty array检查空数组

if (!arr.length) {
  // if the array is empty
}

and for an object (check that it has no keys)对于一个对象(检查它是否没有键)

if (!Object.keys(obj).length) {
  // if the object is empty
}

DEMO演示

Only way I see so far may be ({}).toSource() === o.toSource()到目前为止我看到的唯一方法可能是({}).toSource() === o.toSource()

Example:例子:

var y = {a: 't'};
window.console.log(({}).toSource() === y.toSource());
delete y.a;
window.console.log(({}).toSource() === y.toSource());

EDIT : Oh, nicely found, Andy.编辑:哦,很好发现,安迪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM