如何枚举JavaScript对象的属性? [英] How do I enumerate the properties of a JavaScript object?

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

问题描述

如何枚举JavaScript对象的属性?

How do I enumerate the properties of a JavaScript object?

我实际上想要列出所有已定义的变量及其值,但我已经了解到定义了变量实际上创建了一个窗口对象的属性。

I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.

推荐答案

足够简单:

for(var propertyName in myObject) {
   // propertyName is what you want
   // you can get the value like this: myObject[propertyName]
}

现在,您不会以这种方式获取私有变量,因为它们不可用。

Now, you will not get private variables this way because they are not available.

编辑: @ bitwiseplatypus 是正确的,除非你使用 hasOwnProperty()方法,你将获取继承的属性 - 但是,我不知道为什么熟悉面向对象编程的人会期望更少!通常情况下,提起这件事的人一直受到道格拉斯·克罗克福德(Douglas Crockford)关于此事的警告,这仍然让我感到困惑。同样,继承是OO语言的正常部分,因此它是JavaScript的一部分,尽管它是典型的。

@bitwiseplatypus is correct that unless you use the hasOwnProperty() method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical.

现在,那就是说, hasOwnProperty( ) 对过滤非常有用,但我们不需要发出警告,就像获取继承属性有危险一样。

Now, that said, hasOwnProperty() is useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties.

编辑2: @ bitwiseplatypus 会出现这样的情况:如果有人在您最初​​编写对象(通过其原型)之后的某个时间点向对象添加属性/方法,则会发生这种情况 - 尽管这可能会导致意外行为,我个人并不认为这完全是我的问题。只是一个意见问题。此外,如果我以这样的方式设计东西,即在构造我的对象期间使用原型,然后让代码迭代对象的属性并且我想要所有继承的属性,该怎么办?我不会使用 hasOwnProperty()。然后,让我们说,有人稍后会添加新属性。如果那时事情表现不好,这是我的错吗?我不这么认为。我认为这就是为什么jQuery作为一个例子,已经指定了扩展它的工作方式的原因(通过 jQuery.extend jQuery.fn.extend )。

EDIT 2: @bitwiseplatypus brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use hasOwnProperty(). Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via jQuery.extend and jQuery.fn.extend).

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

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