javascript - 是否可以使用函数输入来创建变量名?

标签 javascript variables angularjs-validation

很确定我的标题具有误导性......哦,好吧。 所以基本上,我正在尝试创建一个游戏,并且我有一堆 arrays ,其名称如 ItemsInG5ArrayItemsInB2Array 其中 G5 B2 是 map 的节点。因此,我想做的是创建一个函数,该函数将为您提供玩家所在的一个特定节点中的项目列表。

function options(location) 
locationPickups: while(true) {
pick = prompt("There are few items laying around.\n" + itemsInG6Array + "\nWould ou like to pick something up?");
...

其中location是节点的名称。有什么简单的东西可以代替 ItemsInG6Array 来使其动态化,使其根据 location 变量而变化。 ItemsIn(位置)数组

最佳答案

这里的典型解决方案是拥有一个带有键的对象,然后动态选择这些键之一。

const example = {
  itemsInG6Array: [],
  itemsInB2Array: [],
}

function options(location) {
  const key = 'itemsIn' + location + 'Array';
  const items = example[key];
  const pick = prompt("There are few items laying around.\n" + items + "\nWould ou like to pick something up?");
}

关于javascript - 是否可以使用函数输入来创建变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56394969/

相关文章:

javascript - 从输入数据作为图像数组传递到 api

objective-c - 接口(interface)中的变量声明问题

javascript - 增加变量名

javascript - AngularJS 表单验证不起作用,显示空表单

javascript - angularjs - 无法使输入无效(对象不支持属性或方法 '$setValidity')

angularjs ng-minlength 验证不起作用,表单仍在提交

javascript - 将 Javascript 函数应用于多个按钮?

javascript - 在应用程序中包含 Polyfill 包

javascript - 是否可以简化此 javascript?

c# - 在类之间发送值的正确方法