Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

javascript - how to assign variable value as variable name in a hash?

I need to define a hash for posting some ajax data using jQuery. The hash will look something like:

var setname = 'set_1';
elements = { set_1: {'beer','water','wine'} };

The challenge I need to solve is 'set-1' (the key of Array elements) should be dynamically named based on the value of var setname.

I want to avoid using eval() of course.. in PHP it can be done using the double dollar sign like this: $$setname, but what's the way to do this in JavaScript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do what you'd like to like so:

var setname = 'set_1', elements = {};
elements[setname] = ['beer','water','wine'];
alert(elements['set_1']); // beer,water,wine

See this in action at http://jsfiddle.net/x5KRD/.

All objects in JS can be accessed using dot notation (obj.method() or obj.property), or bracket notation (obj['method']() or obj['property']). Using bracket notation lets you dynamically specify method/property/key names.

For example, while clumsy, window['alert']('hi') is equivalent to window.alert('hi').

Note that your code won't work as-is, anyways, because you're using object literal notation ({'beer','water','wine'}) to contain an array (it should be in square brackets ['beer','water','wine'] instead). Object literals need to have key-value pairs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...