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.

1
  • 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. Commented Aug 2, 2016 at 16:33

5 Answers 5

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?

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

I don't think this results in what OP has asked for. OP wants e to equal 40.
@evolutionxbox He wants e[0] to be 40, because he wants e to be ` reference to c.
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!

Comments

0

Don't use double quotes.

var d = [a,b,c]

then

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

Comments

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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.