0

if you have something like this

var x='y';
var z='x';

if we want to get value of x (i.e y )from z we can achieve like this

eval(z) which will give you 'y'.

My question is if i am having x as an array like

var x=[a,b,c];
var z='x';

how can i get the x array values like x[0],x[1],x[2] using variable z.

we can't use like eval(z[0]),if we gave like eval[z] we will get like [a,b,c] but i want to access individual array elements directly.what is the way to achieve this.

Please help.

Thanks in Advance.

4 Answers 4

6

If x is a global, you can use window:

window[z][0] === a; // true

...but only if x is a global, and it's frankly not a good idea in any case.

To do this with non-globals, put x on an object:

var obj = {x: [a, b, c]};

...and then use obj:

obj[z][0] === a; // true

In both cases, this works because you can access an object property in JavaScript using either "dot notation" and a literal property name (foo.bar), or "bracketed notation" and a string property name (foo["bar"]). In the second case, you can have any expression for the string.

The reason window works for global variables is that in JavaScript, all global variables are properties of the global object, and on browsers you can reference that global object using the symbol window. (In fact, window itself is a property of the global object, that the object uses to refer to itself.)

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

Comments

3

You can use window

window[z][0]

Comments

1

Just use eval(z)[0]. You have an array just after you do the eval step, not before. So z[0] is not really defined.

Comments

1

Accessing via indexes can happen only after eval.

Try:

var x=['a','b','c'];
var z='x';
eval(z)[0];//this will give a

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.