如何列出JavaScript对象的属性? [英] How to list the properties of a JavaScript object?
问题描述
假设我创建了一个对象:
Say I create an object thus:
var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
检索属性名称列表的最佳方法是什么?即我想最终得到一些变量'键',以便:
What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:
keys == ["ircEvent", "method", "regex"]
推荐答案
在现代浏览器中(IE9 + ,FF4 +,Chrome5 +,Opera12 +,Safari5 +)您可以使用内置的对象。键方法:
In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:
var keys = Object.keys(myObject);
上面有一个完整的polyfill,但简化版是:
The above has a full polyfill but a simplified version is:
var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
或者替换 var getKeys
使用 Object.prototype.keys
,允许您在任何对象上调用 .keys()
。扩展原型有一些副作用,我不建议这样做。
Alternatively replace var getKeys
with Object.prototype.keys
to allow you to call .keys()
on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.
这篇关于如何列出JavaScript对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!