最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - read name of unknown properties - Stack Overflow

programmeradmin1浏览0评论

I have a simple javascript object with several unknown properties containing a value. The problem is that i don't really know the name of the field since it is variable. How can I access this unknown property?

For better understanding I have a simple object like following:

var a = { cat : "meow", dog : "woof"};

I need to read the name and the value of the different properties. I was thinking about something like the following: a.getField(0).name.

I have a simple javascript object with several unknown properties containing a value. The problem is that i don't really know the name of the field since it is variable. How can I access this unknown property?

For better understanding I have a simple object like following:

var a = { cat : "meow", dog : "woof"};

I need to read the name and the value of the different properties. I was thinking about something like the following: a.getField(0).name.

Share Improve this question edited Jul 24, 2011 at 13:39 Quentin 945k132 gold badges1.3k silver badges1.4k bronze badges asked Jul 24, 2011 at 13:30 KuepperKuepper 1,00415 silver badges41 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You can do somethine like this:

for (var member in a) {
    alert('Name: ' + member);
    alert('Value: ' + a[member]);
}

for more info about reflection in JS see here:

http://lpetr/blog/archives/reflection-in-javascript

You could access the properties by name:

for (var key in a) {
    var value = a[key];
}

Demo.

发布评论

评论列表(0)

  1. 暂无评论