tags:

views:

548

answers:

5

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?

+3  A: 

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]);
}
Jim Puls
I now have 3d arrays. If I do this, I may have 4d arrays and I think it may be too complicated.
Billy
+2  A: 

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...

Kai
+1  A: 

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

function perform(arr){
    alert(arr[0]);
}
m_oLogin
+3  A: 

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');
Gumbo
A: 

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])
Eddie Deyo
Just saw Gumbo's answer -- using this is better than using window
Eddie Deyo
Why using this is better than using window?
Billy
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.
Eddie Deyo