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

江枫思渺然 提交于 2019-12-01 00:40:19
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'];

Although you really shouldn't use eval this should help

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!