简体   繁体   English

动态创建名称在Java脚本字符串中的Java脚本数组

[英]Create java script array dynamically whose name is in java script string

I have a collection of arrays which are generated dynamically. 我有动态生成的数组的集合。 What I am trying to do is to implement an AutoComplete functionality. 我想做的是实现自动完成功能。 I want to use those arrays in click event handler, by getting name dynamically and assigning that to local array. 我想在click事件处理程序中使用这些数组,方法是动态获取名称并将其分配给本地数组。 But that is not working (I'm not sure abt my code). 但这是行不通的(我不确定代码是否正确)。 Is there any way to achieve that? 有什么办法可以实现?

Here is my code which I believe should work (which does not work): 这是我认为应该起作用的代码(不起作用):

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script>
    var ga_input1 = new Array('India','Russia','Norway');
    var ga_input2 = new Array('Delhi','Mumbai','Hyderabad');
</script>
<body>
    Countries: <input id="input1"  type="text"/>
    Cities: <input id="input2"  type="text"/>

    <script>
        var arrayTmp = new Array();
        $('input').keydown(function(){
            var id = $(this).attr('id');
            arrayTmp = "ga_"+id; // What I believe here is the values of ga_input1/ga_input2 are assigned to array 'arrayTmp' 
            //alert(arrayTmp[0]);
        });
    </script>
</body>

You can put that arrays in a "Map" and later fetch them from it easily. 您可以将这些数组放在“地图”中,以后可以轻松地从中获取它们。

Here's how it's done: 这是完成的过程:

var countryMap = {};
countryMap["Europe"] = ['Russia', 'England', 'Norway'];
countryMap["America"] = ['USA', 'Canada', 'Mexico'];

....

var arrayTmp = countryMap["America"];
alert(arrayTmp[0]); //USA
alert(arrayTmp[1]); //Canada
alert(arrayTmp[2]); //Mexico

All global variables are members of the window object, so: 所有全局变量都是window对象的成员,因此:

arrayTmp = window["ga_"+id];

But I'd personally put the data in an object like this: 但是我个人将数据放在这样的对象中:

data = {
    'input1': ['India','Russia','Norway'],
    'input2': ['Delhi','Mumbai','Hyderabad']
};
...
arrayTmp = data[id];

What you have in arrayTmp is just a string "ga_input1" . 您在arrayTmp中只有字符串"ga_input1" Instead, try eval("arrayTmp=ga_"+id); 而是尝试eval("arrayTmp=ga_"+id); .

eval('var arrayTmp = ga_' + id); eval('var arrayTmp = ga_'+ id); alert(arrayTmp[0]); alert(arrayTmp [0]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM