0

I'm trying to access different variables depending on user input. To simplify, let's say I have three variables, x1 = "variable 1", x2 = "variable2" and x3 = "variable3". I want to be able to call a different variable, depending on another variable, y. Let's say y=2, that means I want to get x2.

I tried something like console.log(x[y]), but that doesn't seem to work. I didn't find anything on this topic anywhere, so I don't know if it's possible or not, or if that's even how you would solve this problem.

For those who are interested, I'm trying to access different Discord.RichEmbed()s depending on the variable, and I don't think I can store those in an array. If that is somehow possible, please let me know. If I forgot to explain something let me know and I'll add it or answer any questions you might have

Thanks in advance ^^

EDIT: It would also work if y="x2" and if I could then somehow get the contents of x2 that way.

Aci
  • 546
  • 5
  • 22
  • Why do my comments keep getting deleted :| – Aci Mar 28 '20 at 12:10
  • 1
    Does this answer your question? "[Use dynamic variable names in JavaScript](//stackoverflow.com/q/5117127/90527)", "["Variable" variables in JavaScript](//stackoverflow.com/q/5187530/90527)" – outis May 12 '22 at 20:23

1 Answers1

1

You are exhibiting a fundamental misunderstanding of JavaScript principles and my feeling is that you are essentially "hacking together" something for Discord.

I don't know if this will help you because there should probably be more context posted.

There are many ways to accomplish this.

You could create a method that has the source of variables and returns a reference to one of them based on a y variable passed as an argument.

const retrieveX = (y) => {
  const source = {
    x1: 'variable1',
    x2: 'variable2',
    x3: 'variable3',
  }
  return source[y]
}
retrieveX('x1')
Miaplacidus
  • 525
  • 3
  • 7
  • 1
    Actually no, I'm just trying to make a fun Discord bot in my spare time ^^ Here's more context: I'm trying to do "page switching" in an embed, which means I have pre-defined all possible "pages" of the embed as individual embeds. When the user reacts to the message, it's supposed to advance a page, so edit the message with another embed. I have a variable i storing the current page number and each embed is simple called "embed" with the number behind it. If I do it like sugessted, it gets the NAME of the embed, not the embed. So logging shows "embed2", not the contents of the embed. – Aci Mar 24 '20 at 22:49
  • 1
    Firgued out with the help of the code you provided, thanks a ton! ^^ – Aci Mar 24 '20 at 23:02