如何找到分配给随机选择的变量的特定数组?

How can I find a specific array assigned to a randomly selected variable?

所以我正在尝试为文本角色扮演游戏制作一个功能,允许人们单击“漫游”按钮并最终到达当前位置附近的随机位置。我创建了几个数组,其中包含位置靠近其他位置的信息,我希望能够按下一个按钮,生成一个新位置,将该位置保存为当前位置,并生成一个新的漫游结果下次按下按钮时的新位置。

//Starting area locations
    const startingAreaLocations = [Clearing, BigForrest, SmallForrest, Cliffs, Cave, Pond, Start, River, TownEnterance];
    const locationsNearStart = [BigForrest, Cliffs, Cave];
    const locationsNearBigForrest = [Start, Clearing, River];
    const locationsNearCliffs = [Start, Cave, River];
    const locationsNearCave = [Cliffs, Pond, River, Start];
    const locationsNearClearing = [BigForrest, River, Start];
    const locationsNearSmallForrest = [Pond, River, TownEnterance];
    const locationsNearPond = [SmallForrest, Cave, River];
    const locationsNearRiver = [BigForrest, Cliffs, Cave, Clearing, SmallForrest, Pond, TownEnterance];
    const locationsNearTowerEnterance = [SmallForrest, River];

我目前的问题是,当我生成并加载一个新位置时,我不知道如何告诉系统它应该为下一个位置引用哪个数组。我试着给变量命名,这样我就可以将位置名称变量添加到一个字符串中并得出数组名称,但即使我把它放在 JSON.parse() 中,它也会读取字符串,而不是我的内容数组。

function wander(location) {
                wanderLocation = location[Math.floor(Math.random()*location.length)];
                console.log(wanderLocation);
                locationsNearCurrentArea = "locationsNear" + wanderLocation.name;
                console.log(locationsNearCurrentArea);
                
                callPannel(wanderLocation.string);
            }

我怎样才能更好地制作一个功能,让我在这样的地点之间来回穿梭?

我会为此使用显式数据结构而不是一堆变量。 Map 以当前位置为键,以数组中的附近位置为值就足够了

const nearbyLocations = new Map([
//[ key,        [ values, ... ] ],
  [ Start,      [ BigForrest, Cliffs, Cave ] ],
  [ BigForrest, [ Start, Clearing, River ] ],
  [ Cliffs,     [ Start, Cave, River ] ],
  // etc
])

然后你可以使用类似这样的方法来获取附近的随机位置

const wander = (currentLocation) => {
  const nearby = nearbyLocations.get(currentLocation)
  return nearby?.[Math.floor(Math.random() * nearby?.length)]
}

您至少应该将数据放在JSON、对象或列表中。下面是一个使用对象的例子:

let data = {
  startingAreaLocations: ["Clearing", "BigForrest", "SmallForrest"],
  locationsNearStart: ["BigForrest", "Cliffs", "Cave"],
  locationsNearBigForrest: ["Start", "Clearing", "River"],
};
let newLocation = "River";
let newWander = ["SmallForrest", "BigForrest"];

let dataKey = Object.values(data);
data[Object.keys(data)[Object.keys(data).length - 1]].forEach((e) => {
  if (e === newLocation) {
    data[`locationsNear${e}`] = newWander;
  }
});

console.log(data);