Reputation: 23
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.
Upvotes: 2
Views: 94
Reputation: 2047
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]);
Upvotes: 0
Reputation: 81
Don't use double quotes.
var d = [a,b,c]
then
console.log(e[0][0]) will return the element you want
Upvotes: 0
Reputation: 141829
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.
Upvotes: 3
Reputation: 115222
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]);
eval()
method but I don't prefer that method.
Refer : Why is using the JavaScript eval function a bad idea?
Upvotes: 6
Reputation: 10254
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!
Upvotes: 2