Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/403.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 访问JSON数组时遇到问题_Javascript_Arrays_Json - Fatal编程技术网

Javascript 访问JSON数组时遇到问题

Javascript 访问JSON数组时遇到问题,javascript,arrays,json,Javascript,Arrays,Json,我有一个JSON文件,其中包含来自每个国家的足球队。 例如: 我的程序收到一个带有国家名称的用户输入,我随机给他们一个来自所选国家的团队,如下所示: var SelectedCountry= $('#UserInput').val(); // "Spain" or "England" alert(FootballTeams.SelectedCountry[Math.floor(Math.random()*FootballTeams.countryf.length)]); 它似乎不起作用,但如果

我有一个JSON文件,其中包含来自每个国家的足球队。 例如:

我的程序收到一个带有国家名称的用户输入,我随机给他们一个来自所选国家的团队,如下所示:

var SelectedCountry= $('#UserInput').val(); // "Spain" or "England"
alert(FootballTeams.SelectedCountry[Math.floor(Math.random()*FootballTeams.countryf.length)]);
它似乎不起作用,但如果直接插入字符串,我可以访问数组:

alert(FootballTeams."Spain"[Math.floor(Math.random()*FootballTeams.countryf.length)]);

如何使第一个选项起作用?

当使用变量访问对象的
键时,应该这样尝试

alert(FootballTeams[SelectedCountry][Math.floor(Math.random()*FootballTeams.countryf.length)]);

对代码使用代码格式,而不是引号。谢谢,它工作得很好。
alert(FootballTeams[SelectedCountry][Math.floor(Math.random()*FootballTeams.countryf.length)]);