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

时间:2019-05-31 12:16:01

标签: javascript variables angularjs-validation

可以肯定,我的标题有误导性……哦。 因此,基本上,我正在尝试创建一个游戏,并且有一堆arrays,它们的名称为ItemsInG5ArrayItemsInB2Array,其中G5B2是节点地图。因此,我正在尝试创建一个函数,该函数将为您提供播放器所在的特定节点中的项目列表。

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(location)Array

1 个答案:

答案 0 :(得分:1)

这里的典型解决方案是使对象具有键,然后动态选择其中一个键。

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?");
}