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

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

问题描述

如何枚举 JavaScript 对象的属性?

How do I enumerate the properties of a JavaScript object?

我实际上想列出所有定义的变量及其值,但我了解到定义变量实际上会创建 window 对象的属性.

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) 对此的警告,这仍然让我有些困惑.同样,继承是面向对象语言的正常部分,因此也是 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.extendjQuery.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天全站免登陆