2

var a = [10,20,30,40];
var b = [11,22,33,44];
var c = [40,30,20,10];

var d = ["a","b","c"];

var e = d[2];

console.log(e[0]);

How do I make javascript treat string value of variable e (i.e. string 'c') as name of array so e[0] would return 40 and not the character at position [0]. Thank you for your support and sorry if it's a dumb question.

  • OP - you need to put the three arrays into an object or use the window object (not advised). What you're asking for is a [dynamic variable name](http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript). – evolutionxbox Aug 02 '16 at 16:33

5 Answers5

6

Instead of string put the reference of the array as the element.

var d = [a, b, c];

var a = [10, 20, 30, 40];
var b = [11, 22, 33, 44];
var c = [40, 30, 20, 10];

var d = [a, b, c];

var e = d[2];

console.log(e[0]);


Another way is to use eval() method but I don't prefer that method.

Refer : Why is using the JavaScript eval function a bad idea?

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
3

You would need to use eval:

var e = eval(d[2]);

However, the fact that you need to use eval usually means you've done something else wrong. You would most likely be better off with a single variable containing an array of arrays, instead of several variables each containing an array. Pranav C Balan's answer is one way to create an array of arrays from your individual arrays.

Community
  • 1
  • 1
Paul
  • 139,544
  • 27
  • 275
  • 264
2

You can do this if your arrays are keys of an object:

var arrays = {
    a: [10, 20, 30, 40],
    b: [11, 22, 33, 44],
    c: [40, 30, 20, 10],
}

var d = ['a', 'b', 'c'];

var e = d[2];

console.log(arrays[e][0]); // Will output "40".

This avoids the use of eval() that is potentially unsafe!

OR If you really need that a, b and c be an variable instead of an object key, you can do as @pranav answer:

var d = [a, b, c];

This will create references for your original arrays, then you could do:

console.log(d[2][0]); // Will output "40" too!
Elias Soares
  • 9,884
  • 4
  • 29
  • 59
0

Don't use double quotes.

var d = [a,b,c]

then

console.log(e[0][0]) will return the element you want 
0

In the way you want, you can do it with this keyword

var a = [10,20,30,40];
var b = [11,22,33,44];
var c = [40,30,20,10];

var d = ["a","b","c"];

var e = this[d[2]];

console.log(e[0]);
Aren Hovsepyan
  • 1,947
  • 2
  • 17
  • 45