how to create and assign a value to a variable created dynamically?

后端 未结 3 1941
闹比i
闹比i 2021-01-07 03:27

I\'m trying to get this to work:

function whatever(arg) {
  eval(arg) + \'_group\' = [];
}

The purpose is to have only 1 function instead h

相关标签:
3条回答
  • 2021-01-07 03:41
    function whatever(arg) {
      window[arg + '_group'] = [];
    }
    

    This will set a_group, b_group as global variable.

    To access those variable use:

    window['a_group'], window['b_group'] and so on.

    According to edit

    In your switch you should use break;.

    switch(field_name) {
        case 'states':
            use = 'state';
            break;
        case 'cities':
            use = 'city';
            break;
        case 'neighborhoods':
            use = 'neighborhood';   
            break;     
    }
    

    Using local Object (without window object) and better

    var myObject = {};
    
    function whatever(arg) {
      myObject[arg + '_group'] = [];
      // output: { 'a_group' : [], 'b_group' : [], .. }
    }
    
    // to set value
    myObject[arg + '_group'].push( some_value );
    
    // to get value
    myObject[arg + '_group'];
    
    0 讨论(0)
  • 2021-01-07 03:45

    Just to increase @theparadox's answer.
    I prefer to use the following way to make a switch.

    var options =  {
        'states' : 'state',
        'cities': 'city',
        'neighborhoods': 'neighborhood'    
    };
    use = options[field_name];
    

    demo

    Or if you just want to remove the last letter, you can do this.

    use = field_name.slice(0,-1);

    demo

    0 讨论(0)
  • 2021-01-07 04:00

    Although you really shouldn't use eval this should help

    eval(arg + '_group') = [];

    0 讨论(0)
提交回复
热议问题