Is it possible to use function input to create a variable name?

Issue

Pretty sure that my title is misleading… Oh well.
So basically, I’m trying to create a game and I have a bunch of arrays with names like ItemsInG5Array, ItemsInB2Array where G5 and B2 are nodes of the map. So, what I’m trying to do is to create a function that will give you a list of items in one specific node where the player is.

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

Where location is the name of the node. Is there anything simple I can put instead of ItemsInG6Array to make it dynamic, to make it change depending on the location variable.
ItemsIn(location)Array

Solution

The typical solution here is to have an object with keys, and then dynamically pick one of those keys.

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

Answered By – Nicholas Tower

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.