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?
If you mean #, it's invalid to use as part of a variable name because it's a punctuation mark. You wouldn't use a ',' either. It's not a mixed meaning thing like a '.
Definition. Hash Variables gives users greater flexibility and freedom in accessing useful information or relevant run-time values from the system. A hash variable is a special hash-escaped keyword that can be used in : Form Builder. Datalist Builder.
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.
var setname = 'set_1',
elements = {};
elements[setname] = ['beer','water','wine'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With