组合变量值和字符串以在另一个变量名中使用

Combine variable value and string to use in another variable name

我需要将一个变量值和一个字符串值合二为一。问题出在功能上。我正在尝试在“resources”变量中提取资源名称,这需要在末尾与“Amount”结合在一个名为“resourceName”的新变量中。例如“FoodAmount”,但当我尝试在我的函数中使用它时,它最终返回未定义。

如有任何帮助,我们将不胜感激

var resources = [
  "Food",
  "Wood",
  "Stone",
  "Coal",
  "Copper",
  "Silver",
  "Gold",
  "Diamonds"
];

var playerData = [
  {"foodName":"Food", "FoodAmount":"100"},
  {"woodName":"Wood", "WoodAmount":"0"},
  {"stoneName":"Stone", "StoneAmount":"0"},
  {"coalName":"Coal", "CoalAmount":"0"},
  {"copperName":"Copper", "CopperAmount":"0"},
  {"silverName":"Silver", "SilverAmount":"0"},
  {"goldName":"Gold", "GoldAmount":"0"},
  {"diamondsName":"Diamonds", "DiamondsAmount":"0"},
]

function updateResources() {
    for (var i = 0; i <= playerData.length - 1; i++) {
        resourceName = resources[i] + "Amount";
        console.log(playerData[i].resourceName); // Returns undefined??
        document.getElementById(resources[i]).innerHTML = playerData[i].resourceName; // Will also return undefined but should be equel to FoodAmount for the first one and so on
    }
}

您必须使用 playerData[i][resourceName](注意方括号 [...] 而不是圆点 .)。 object.property 对于 object["property"] 只是 shorthand 并且不通过变量 property 而是通过字符串 "property" 索引对象,它产生 undefined因为您的所有对象都没有 "resourceName" 属性 集合。

试试这个:

var resources = [
  "Food",
  "Wood",
  "Stone",
  "Coal",
  "Copper",
  "Silver",
  "Gold",
  "Diamonds"
];

var playerData = [
  {"foodName":"Food", "FoodAmount":"100"},
  {"woodName":"Wood", "WoodAmount":"0"},
  {"stoneName":"Stone", "StoneAmount":"0"},
  {"coalName":"Coal", "CoalAmount":"0"},
  {"copperName":"Copper", "CopperAmount":"0"},
  {"silverName":"Silver", "SilverAmount":"0"},
  {"goldName":"Gold", "GoldAmount":"0"},
  {"diamondsName":"Diamonds", "DiamondsAmount":"0"},
]

function updateResources() {
    for (var i = 0; i <= playerData.length - 1; i++) {
        resourceName = resources[i] + "Amount";
        console.log(playerData[i][resourceName]); 
    }
}

因为您有一个字符串,所以您需要将键作为数组调用。