1

I have several arrays in Javascripts, e.g.

a_array[0] = "abc";
b_array[0] = "bcd";
c_array[0] = "cde";

I have a function which takes the array name.

function perform(array_name){
 array_name = eval(array_name);
 alert(array_name[0]);
}
perform("a_array");
perform("b_array");
perform("c_array");

Currently, I use eval() to do what I want.
Is there any method not to use eval() here?

asked Jun 4, 2009 at 19:01
1
  • Somebody needs to answer the Title of OP. Commented Mar 3, 2022 at 20:52

5 Answers 5

7

You can either pass the array itself:

function perform(array) {
 alert(array[0]);
}
perform(a_array);

Or access it over this:

function perform(array_name) {
 alert(this[array_name][0]);
}
perform('a_array');
answered Jun 4, 2009 at 19:06
Sign up to request clarification or add additional context in comments.

Comments

4

Instead of picking an array by eval'ing its name, store your arrays in an object:

all_arrays = {a:['abc'], b:['bcd'], c:['cde']};
function perform(array_name) {
 alert(all_arrays[array_name][0]);
}
answered Jun 4, 2009 at 19:04

1 Comment

I now have 3d arrays. If I do this, I may have 4d arrays and I think it may be too complicated.
2

Why can't you just pass the array?

function perform(array){
 alert(array[0]);
}
perform(a_array);
perform(b_array);
perform(c_array);

Or am I misunderstanding the question...

answered Jun 4, 2009 at 19:05

Comments

1

why don't you pass your array as your function argument?

function perform(arr){
 alert(arr[0]);
}
answered Jun 4, 2009 at 19:05

Comments

0

I believe any variables you create are actually properties of the window object (I'm assuming since you used alert that this is running in a web browser). You can do this:

alert(window[array_name][0])
answered Jun 4, 2009 at 19:14

3 Comments

Just saw Gumbo's answer -- using this is better than using window
Why using this is better than using window?
Because then it works in any context, browser or not. Also, I'm not sure if local variables being properties of window is standard across all browsers or not. If not, using this will continue to work, where window would not. In general, it's just less likely to cause errors down the road.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.