in CoffeeScript, how can I use a variable as a key in a hash?

后端 未结 6 2081
野趣味
野趣味 2021-01-07 16:00

eg:

\"wtf\"

So:

foo = \"asdf\"
{foo: \"bar\"}
eval foo

# how do I g         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-07 16:54

    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 },
    

提交回复
热议问题