访问JSON数组有问题

Having trouble accessing JSON array

本文关键字:有问题 数组 JSON 访问      更新时间:2023-09-26

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

var FootballTeams = {  
   "Spain":[  
      "RealMadrid",
      "Barcelona",
      "Valencia"
   ],
   "England":[  
      "ManchesterCity",
      "Arsenal",
      "Chelsea",
      "ManchesterUnited",
      "Liverpool"
   ]
};

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

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

如何使第一个选项工作?

当使用变量访问key的对象时,您应该尝试这样做。

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