Is it possible to dynamically select a variable based on the value of another variable in JavaScript? For example, let's say I have 4 variables:
var one = 'Apple',
two = 'Orange',
three = 'Banana',
selector = prompt('Type one, two, or three');
console.log(`You chose ${whatever string is contained within selector}`);
Is it possible to console.log
the variable that has the name matching the string contained in selector
?
Example: user inputs "one", console.log displays Apple, user inputs two, console.log displays Orange, etc.
Obviously this can be done with an if
or a switch
, and with only 3 variables to differentiate between that wouldn't be too hard. However, this is for a Discord bot I'm building, and in the process I am finding it would be helpful for debugging purposes if I could ask the bot to output the value of a given variable at a certain point in the runtime. I'm hoping to write some bit of code that will allow me to input something like !print someVariableName
and my code will call a function which prints the value contained in the variable whose name is contained in someVariableName
at that time.
I'm using Node.js, if that makes a difference - maybe there's an NPM package that does this already.