how to create and assign a value to a variable cre

2019-02-15 18:48发布

I'm trying to get this to work:

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

The purpose is to have only 1 function instead having three with basically the same content but with different variable names.

At the end I want to have something like:

a_group = [];
b_group = [];

Doing this way, I'm getting the error:

ReferenceError: Invalid left-hand side in assignment

EDIT

Here is the original function that I'm trying to make work. But it won't work.

function collect_all_values_for(field_name) {

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

    window[field_name + '_group'] = [];

    n_fields = $('[id^=' + use + '_]').length-1;

    i = 0;
    field_value = 0;
    for (i = 0; i<= n_fields; i++) {

        if (i == 0) {
            field_value = $('#' + use).val(); 
        }else{
            field_value = $('#' + use + '_id' + i).val();
        }

        //states_group.push(field_value);
        window[field_name + '_group'].push(field_value);
    }

}

Looking on the console output:

states_group
[undefined, undefined, undefined]

And then I should be able to call it as:

collect_all_values_for('states');
collect_all_values_for('cities');
collect_all_values_for('neighborhoods');

Thanks in advance.

3条回答
\"骚年 ilove
2楼-- · 2019-02-15 18:52

Although you really shouldn't use eval this should help

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

查看更多
萌系小妹纸
3楼-- · 2019-02-15 18:56

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

查看更多
Lonely孤独者°
4楼-- · 2019-02-15 19:09
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'];
查看更多
登录 后发表回答