2

This is a very stripped down example of what I'm trying to do. These arrays are generated with server side code and I can't know which arrays will be there except that they will always be 'array' followed by a number.

var array1 = ['cat','dog','fish','bird'];
var array2 = ['taco','pizza','burger','salad'];
var array3 = ['maple','elm','pine'];

The user selects an option from select-1

<select id="select-1" onchange="getArray()">
    <option value="1">Pets</option>
    <option value="2">Foods</option>
    <option value="3">Trees</option>
</select>

Then I need my function to access the correct array corresponding to the value of select-1. Every option that appears in select-1 will have a corresponding array.

function getArray() {
    var x = document.getElementById("select-1").value;

    //how do I access "arrayx"?

    var y = arrayx[0];
}

How can I write the function to get a value from the correct array? I need something like

arrayname = 'array' + x;

but I can't figure out how to get there from here.

Here is a fiddle that's set up to experiment with: http://jsfiddle.net/6yor1kp5/9/

Anonymous Man
  • 2,776
  • 5
  • 19
  • 38

3 Answers3

5

If it is in the global context in a browser, you can use window[arrayname].

e.g.

var y = window["array"+x][0];

in your fiddle.

tevemadar
  • 12,389
  • 3
  • 21
  • 49
2

You could just follow @Pointy and surround the arrays in another array. In your current situation you'd have to append the arrays into arrayx when you load the arrays from the server.

var arrayx = [
    ['cat','dog','fish','bird'],
    ['taco','pizza','burger','salad'],
    ['maple','elm','pine']
];
0

You can use eval function for this -

var array1 = ['cat','dog','fish','bird'];
var array2 = ['taco','pizza','burger','salad'];
var array3 = ['maple','elm','pine'];

//if you want to use array1

var array = eval("array" + 1);

console.log(array);

But one should never ever use eval

Vivek
  • 1,465
  • 14
  • 29