如何检查对象在JavaScript中是否有任何属性? [英] How to check if object has any properties in JavaScript?

查看:131
本文介绍了如何检查对象在JavaScript中是否有任何属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我宣布

var ad = {}; 

如何检查此对象是否包含任何用户定义的属性?

How can I check whether this object will contain any user-defined properties?

推荐答案

您可以按如下方式遍历对象的属性:

You can loop over the properties of your object as follows:

for(var prop in ad) {
    if (ad.hasOwnProperty(prop)) {
        // handle prop as required
    }
}

使用 hasOwnProperty() 方法,确定对象是否具有指定的属性作为直接属性,而不是从对象的原型链继承。

It is important to use the hasOwnProperty() method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.

来自评论: 您可以将该代码放入函数中,并在它到达有注释的部分时返回false

性能测试

测试Of Object.Keys vs For..In测试任何属性时

这篇关于如何检查对象在JavaScript中是否有任何属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆