2

Let's say I have this;

var str = "array1";
var array1 = [a,b,c];

What I am looking for is a way to write something like this (where answer will be "a");

var answer = str.value[0];

i.e. I want to be able to access the array "array1" by using the text stored in the string str.

Thank you for any suggestions. (If you understand what I am asking from the above, and there is an easy answer there is no need to read any further)

My problem in detail:

I have some option buttons on a form. When any one of them is clicked I run a function and display the array relating to the button clicked. Each button has a different 2D array relating to it.

My idea was to pass a value identifying the array to use by passing the value "array1option" if array1 was desired. Then in the function it would not matter which array was picked as I would simply chop off the "option" part of the string and store the resulting array into an array (DesiredArray). The rest of the code would be a generic code for displaying the whole 2D array DesiredArray.

My backup plan would be to use a 3D array (is that supported in Javascript) But I would find it much easier to have the data in separate 2D tables for the purposes of editing.

I'm sure the most effective way to do it would be via linking a database but I could not find any really simple example showing how I could do this and I am fairly new to Javascript.

1
  • When you click the button, pass the array to the function not the name of the array. Commented Jul 6, 2014 at 10:46

2 Answers 2

1

Pass the array object itself instead of the name. Approximately (and assuming you use jQuery)

var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];

function myFunction(arr) {
   console.log( arr[0]);
}

// event handlers for button1 and button2

$('#myButton1').on('click', function( evt) {
    myFunction( array1):
);

$('#myButton2').on('click', function( evt) {
    myFunction( array2):
);
1
  • Ok, I do feel a little stupid now, that irradiates my problem, Thanks. I won't put it as the accepted answer as it didn't answer the initial question. But I will use it, thank you. Commented Jul 6, 2014 at 23:00
-1

The easiest way to refer to variables like that is to declare your array as a property on another object:

var myStr = 'array1',
    myObj = {
        array1: ['a', 'b', 'c'],
        array2: ['d', 'e', 'f']
    };

console.log( myObj[myStr][0] );  // "a"
1
  • Thanks, nice and simple solution to my stated problem. I will remember this. (But use vogomatix's solution as it fits my particular problem better) Commented Jul 6, 2014 at 22:56

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.