in CoffeeScript, how can I use a variable as a key in a hash?
eg:
So:
foo = "as开发者_如何学Pythondf"
{foo: "bar"}
eval foo
# how do I get {"asdf": "bar"} ?
# this will throw parse error:
{(eval foo): "bar"}
This is a simple syntax question: how do I get CoffeeScript to construct a hash dynamically, rather than doing it by hand?
For anyone that finds this question in the future, as of CoffeeScript 1.9.1 interpolated object literal keys are supported!
The syntax looks like this:
myObject =
a: 1
"#{ 1 + 2 }": 3
See https://github.com/jashkenas/coffeescript/commit/76c076db555c9ac7c325c3b285cd74644a9bf0d2
Why are you using eval
at all? You can do it exactly the same way you'd do it in JavaScript:
foo = 'asdf'
h = { }
h[foo] = 'bar'
That translates to this JavaScript:
var foo, h;
foo = 'asdf';
h = {};
h[foo] = 'bar';
And the result is that h
looks like {'asdf': 'bar'}
.
CoffeeScript, like JavaScript, does not let you use expressions/variables as keys in object literals. This was support briefly, but was removed in version 0.9.6. You need to set the property after creating the object.
foo = 'asdf'
x = {}
x[foo] = 'bar'
alert x.asdf # Displays 'bar'
Somewhat ugly but a one-liner nonetheless (sorry for being late):
{ "#{foo}": bar }
If you're looking to use Coffeescript's minimal syntax for defining your associative array, I suggest creating a simple two line method to convert the variable name
keys into the variable values after you've defined the array.
Here's how I do it (real array is much larger):
@sampleEvents =
session_started:
K_TYPE: 'session_started'
K_ACTIVITY_ID: 'activity'
session_ended:
K_TYPE: 'session_ended'
question_answered:
K_TYPE: 'question_answered'
K_QUESTION: '1 + 3 = '
K_STUDENT_A: '3'
K_CORRECT_A: '4' #optional
K_CORRECTNESS: 1 #optional
K_SECONDS: 10 #optional
K_DIFFICULTY: 4 #optional
for k, event of @sampleEvents
for key, value of event
delete event[key]
event[eval(key.toString())] = value
The SampleEvents
array is now:
{ session_started:
{ t: 'session_started',
aid: 'activity',
time: 1347777946.554,
sid: 1 },
session_ended:
{ t: 'session_ended',
time: 1347777946.554,
sid: 1 },
question_answered:
{ t: 'question_answered',
q: '1 + 3 = ',
sa: '3',
ca: '4',
c: 1,
sec: 10,
d: 4,
time: 1347777946.554,
sid: 1 },
Try this:
foo = "asdf"
eval "var x = {#{foo}: 'bar'}"
alert(x.asdf)
精彩评论