如何在散列中将变量值指定为变量名? [英] how to assign variable value as variable name in a hash?
问题描述
我需要定义一个哈希,用于使用jQuery发布一些ajax数据。
哈希值如下所示:
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'} };
我需要解决的挑战是'set-1'(数组元素的关键)应该是根据 var setname
的值动态命名。
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
.
我想避免使用 eval ()
当然.. PHP中的
可以使用这样的双美元符号来完成: $$ setname
,但是什么是在JavaScript中执行此操作的方法?
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?
推荐答案
您可以按照自己喜欢的方式执行此操作:
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
在 http://jsfiddle.net/x5KRD/ 。
可以访问JS中的所有对象使用点符号( obj.method()
或 obj.property
)或括号表示法( obj ['method']()
或 obj ['property']
)。使用括号表示法可以动态指定方法/属性/键名。
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.
例如,虽然笨拙, window ['alert']('hi ')
相当于 window.alert('hi')
。
For example, while clumsy, window['alert']('hi')
is equivalent to window.alert('hi')
.
注意无论如何,你的代码将无法正常工作,因为你正在使用对象文字符号( {'beer','water','wine'}
)来包含一个数组(它应该在方括号 ['beer','water','wine']
中)。对象文字需要有键值对。
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.
这篇关于如何在散列中将变量值指定为变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!