JavaScript 属性反射
首先,让我警告你,我不是 javascript 专家。 我已经发现了一些有关该主题的问题,但几乎所有问题都用相同的解决方案回答。 我有一个简单的自定义 javascript 对象:
var errorMsg ={
msg1 : "x",
msg2 : "y",
msg3 : "z",
msg4 : "t"
}
我想从对象中获取所有属性名称,例如 ["msg1","msg2","msg3","msg4"]。 就像我告诉的,几乎解决方案指向使用 for/in 循环来迭代所有属性名称。但我的应用程序将在 IE6 及更高版本中运行,并且我研究 IE 不支持此循环或至少不支持 IE6。那我能做什么呢? 最后一个问题是,在哪里可以找到好的 javascript 参考资料?我看到该对象有一个返回键的方法,例如 Object.keys() ,我在哪里可以找到一个很好的参考,它为我提供了与 javascript 内置对象相关的所有属性和方法?
First of all, let me warn you that i am not a javascript guru.
I already found a few questions regarding this topic but almost all of them answer with the same solution.
I have a simple custom javascript object:
var errorMsg ={
msg1 : "x",
msg2 : "y",
msg3 : "z",
msg4 : "t"
}
and i want to get all the properties names from the object like ["msg1","msg2","msg3","msg4"].
Like i told almost solution point to the use of the for/in loop to iterate over all properties name. But my app will run in IE6 and above, and i research that IE does not support this loop or at least the IE6. So what can i do ?
The last question is , where can i find a good javascript reference ? I saw that the Object have a method that returns keys like Object.keys() , where can i find a good reference that gives me all the properties and method related with javascript built in objects ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以定义一个通用方法来从任何对象返回键数组,
并使用函数的call方法对errorMsg对象进行操作:
You could define a generic method for returning an array of keys from any object,
and use the function's call method to operate on the errorMsg object:
首先,请参阅 Javascript 是否有增强的 for 循环语法类似于我们刚刚讨论过的 Java 的。但由于您在这里使用的是对象而不是数组,因此并非所有答案都适用。在这里,您需要确保您使用的解决方案涉及
hasOwnProperty
。在参考方面,我总是使用 https://developer.mozilla.org/en/JavaScript /参考。那里列出的所有内容都具有非常高的质量。请注意,并非列出的所有内容都同样适用于所有浏览器。
First, see Does Javascript have an enhanced for loop syntax similar to Java's where we were just discussing this. But since you are using an object instead of an Array here, not all of the answers will apply. Here you will want to be sure that you're using a solution that involves
hasOwnProperty
.In terms of a reference, I always use https://developer.mozilla.org/en/JavaScript/Reference. Everything that is listed there is of very high quality. Just beware that not everything listed will apply equally to all browsers.
如果没有 for-in 选项,您可以使用包含消息对象的数组。您可以通过这种方式使用标准的 for 循环。
不过,您无法再按名称访问消息 - 将消息名称映射到
errorMsg
中的索引可能是解决此问题的方法。If for-in is no option, you could use an array containing message objects. You can use a standard for loop this way.
You can't access the messages by name any more though - mapping message name to an index in
errorMsg
might be a workaround for this.