Javascript using a variable as an array name

I have several arrays in Javascripts like

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

I have a function that takes an array name.

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

I am currently using eval () to do what I want.
Is there a way not to use eval () here?

+1
source share
5 answers

You can either pass an array:

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

Or access it through this:

function perform(array_name) {
    alert(this[array_name][0]);
}
perform('a_array');
+7
source

Instead of selecting an array evalusing its name, save your arrays in an object:

all_arrays = {a:['abc'], b:['bcd'], c:['cde']};
function perform(array_name) {
    alert(all_arrays[array_name][0]);
}
+4
source

Why can't you just pass in an array?

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

Or I do not understand the question ...

+2
source

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

function perform(arr){
    alert(arr[0]);
}
+1
source

I believe that any variables you create are actually properties of the window object (I assume since you used the alert that this works in a web browser). You can do it:

alert(window[array_name][0])
0
source

All Articles