在后端我编写了一些代码来读取文件并输出到JavaScript数组列表,例如,该页面将显示:
<script>
var peanuts = ["1","s","g","3","n"];
var cashewNuts = ["d","a","f","d","n"];
var PecanNuts = ["6","m","3","x","m"];
var BrazilNuts = ["j","n","7","v","s"];
var goingNuts = ["a","e","7","m","y"];
</script>
然后我想根据该页面中其他地方的值使用数组。
例如:
if($('select').val()===0){
alert(firstArray[1]);
}
我的问题是变量名是根据读文件中包含的内容决定的,我无法知道这些信息。有没有办法说出例如
//collect the value from the select and assign it to a var
var varN = $('select').val();
//then collect another variable that has the variable name that
//equals the value of the 'varN'
我知道这看起来很可怕但不幸的是基于我需要做的事情,这是我需要做的事情:(
答案 0 :(得分:2)
如果变量直接在<script>
中声明,则可以使用window[varN]
。
答案 1 :(得分:2)
是。例如,如果您的变量位于全局范围内,则可以执行
var val = window[varN][0];
获得花生:1
如果你这样做
var nuts = {
peanuts : ["1","s","g","3","n"],
cashewNuts : ["d","a","f","d","n"],
PecanNuts : ["6","m","3","x","m"],
BrazilNuts : ["j","n","7","v","s"],
goingNuts : ["a","e","7","m","y"]
}
然后你可以使用
var val = nuts[varN][0];