在后端,我编写了一些代码来读取文件并输出到 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'
我知道这看起来很可怕,但不幸的是,根据我需要做的事情,这就是我需要做的:(
最佳答案
是的。例如,如果您的变量在全局范围内,您可以这样做
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];
关于javascript - 从选择中捕获变量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30642447/