如何为动态创建的变量创建和赋值? [英] how to create and assign a value to a variable created dynamically?

查看:63
本文介绍了如何为动态创建的变量创建和赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图让这个工作:

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 = [];

这样做,我收到错误:

ReferenceError: Invalid left-hand side in assignment

编辑

这是我正在努力工作的原始功能。但它不起作用。

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);
    }

}

查看控制台输出:

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');

提前致谢。

推荐答案

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

这将设置 a_group b_group 作为全局变量。

This will set a_group, b_group as global variable.

要访问这些变量,请使用:

To access those variable use:

window ['a_group'],窗口['b_group'] 依此类推。

在你的开关中你应该使用 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'];

这篇关于如何为动态创建的变量创建和赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆