Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
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.

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

Thanks a lot!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!