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

Javascript - access object member when identifier string is stored in a var - Stack Overflow

programmeradmin1浏览0评论

I've got a pretty simple question (and tentative answers), I just want to see if maybe there is a better answer out there.

How can you access an object member in javascript when the member identifier is stored in another variable? Example:

state = 'sync';

messages = {
  'sync': 'asdf',
  'ready': 'asdf',
  'plete': 'asdf'
};

Possibilities: 1. message = eval('messages.' + state);

  1. turn message into a hash (in prototype or jquery--not sure about jquery) and access through the framework's method

What other ways are there? Anything cleaner? In php it would be simple $message = $messages->$sync.

I'm sure this question has been answered many times but it is tough to search for... all I get are eval responses when I search for 'variable variables'

Thanks

I've got a pretty simple question (and tentative answers), I just want to see if maybe there is a better answer out there.

How can you access an object member in javascript when the member identifier is stored in another variable? Example:

state = 'sync';

messages = {
  'sync': 'asdf',
  'ready': 'asdf',
  'plete': 'asdf'
};

Possibilities: 1. message = eval('messages.' + state);

  1. turn message into a hash (in prototype or jquery--not sure about jquery) and access through the framework's method

What other ways are there? Anything cleaner? In php it would be simple $message = $messages->$sync.

I'm sure this question has been answered many times but it is tough to search for... all I get are eval responses when I search for 'variable variables'

Thanks

Share Improve this question edited Feb 27, 2010 at 23:43 Çağdaş Tekin 16.7k4 gold badges51 silver badges59 bronze badges asked Feb 27, 2010 at 23:40 joshsjoshs 1,9201 gold badge17 silver badges20 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9
var message = messages[state];

Every object in JavaScript is not only an object in the more usual sense, but it is also a dictionary populated by its members.

发布评论

评论列表(0)

  1. 暂无评论