-2

So I have array with some names. And names are other strings. Look at my code and you will know what I am trying to do. I don't wanna use array in array and switch.

var str = ["jun", "ede", "sin", "ddw"];
var jun = ["jun1", "jun2"];
var ede = ["ede1", "ede2"];
showValue(str[1]);
function showValue(name) {
  return name[0];
}

I want to return "ede1". How I can do it?

Linus Oleander
  • 17,746
  • 15
  • 69
  • 102
Eryczal
  • 23
  • 2
  • 2
    http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript – adeneo Dec 06 '15 at 16:03
  • 1
    You can create sub-arrays before main array like this: `var jun = ["jun1", "jun2"]; var str = [jun, ede, sin, ddw];` Where "jun" is array – Michael Dec 06 '15 at 16:04

2 Answers2

1

According to what you are trying to achieve:

 var jun = ["jun1", "jun2"];
 var ede = ["ede1", "ede2"];
 var str = [jun, ede, "sin", "ddw"];

/* Here "ede" and ede are different. "ede" is a string and ede is a variable */


showValue(str[1]);  // str[1] is ede

function showValue(name) {
     console.log(name[0]); // ede[0] is "ede1"
 }

Console displaying ede1.

You have to pass those variables in str array.

This is one way of doing it and easier way to do it unless you understand the window object that is the global object of javascript.

marukobotto
  • 759
  • 3
  • 12
  • 26
1

Try this:

var str = ["jun", "ede", "sin", "ddw"];
var jun = ["jun1", "jun2"];
var ede = ["ede1", "ede2"];
showValue(str[1]);
// => "ede1"

function showValue(name) {
  return window[name][0];
}
Johan Karlsson
  • 6,419
  • 1
  • 19
  • 28