Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Identifying an array using a string JavaScript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thanks a lot!

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading