0

I am trying use the value entered in an input as the name of the array I want to query.

This is my input:

<input id="enter" type="text">

This is what I have now.

  $('#enter').on('keyup', function (e) {
    var ex01 = ['up', 'down', 'left']
    var ex02 = ['blue', 'green', 'red']
    if (e.keyCode === 13) {
      var matchingArray = 'ex' + ($(this).val());
      var firstValue = matchingArray[0];
      var secondValue = matchingArray[1];
      console.log(firstValue);
      console.log(secondValue);
    }
  });

My intent would be that if "01" is entered it would return the first and second values in ex01:

up
down

Instead I'm getting the first and second characters from the string "ex01".

e
x
  • Does this answer your question? [Use dynamic variable names in JavaScript](https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript) – Heretic Monkey Jul 08 '21 at 16:39
  • `matchingArray` is a string, so `[0]` gets the first code point of that string. What you want is the value of the variable that has the name that matches the string you constructed. I would use an object, like `var ex = { ex01: ['up','down'left'[, ex02: ['blue','green','red'] };` then use `ex[matchingArray][0]` to get 'up'. – Heretic Monkey Jul 08 '21 at 16:43
  • @HereticMonkey Thanks so much for your explanation! Your suggestion worked perfectly. – TahomaSans Jul 08 '21 at 18:06

0 Answers0