Home > Enterprise >  Identifying an array using a string JavaScript
Identifying an array using a string JavaScript

Time:06-17

I am having difficulties with returning a pre-declared array from user feedback. This is an exercise meant to help me understand how to take user input using a drop-down in HTML and return a value based on a script.

What I want the second part of the script to do is return the array whose name is the string selected by the user.

/* This part works in returning the array I need, but it requires that they are placed 
inside an object and returning them based on the key,
which I would want to avoid. */

const obj = { att: [1, 1, 1, 1], btt: [2, 2, 2, 2], ctt: [3, 3, 3, 3], dtt: [4, 4, 4, 4] };
function getOption() {
  let choice = document.getElementById("mySelect").value;
  function pick(name) {
    return obj[String(name)];
  }
  document.getElementById("demo").innerHTML = pick(choice);
// Drop-down choice "att", output "[1,1,1,1]".
}

/* Here, although the arrays are named One and Two and I return a string that is either
"One" or "Two", JS doesn't seem to notice that those are array names
and returns the string themselves. */

const One = ['a','a'];
const Two = ['b','b'];
function getSecondOption() {
  let choice = document.getElementById("mySelectZwei").value;
  function pick(name) {
    return String(name);
  }
  document.getElementById("demoZwei").innerHTML = pick(choice);
// Drop-down choice "One", output "One".
}

I have tried not using String() in the second part but it did not change anything. Array.isArray() doesn't seem to work, either, so it's clear that the editor doesn't see a connection between the array names and the strings.

Would appreciate any feedback telling me what to look into or suggestions for solutions.

Thanks a lot!

CodePudding user response:

If I'm not mistaken you could use var instead of const this way variables would not be scoped and attached to the global object window and so be accessible using window[name].

try

var One = ['a','a'];
var Two = ['b','b'];
function getSecondOption() {
  let choice = document.getElementById("mySelectZwei").value;
  function pick(name) {
    return window[name];
  }
  document.getElementById("demoZwei").innerHTML = pick(choice);
}
  • Related