Badrush
Badrush

Reputation: 1287

How to pass variables as the name of array into function in Javascript

From my DOM element, I let the user choose a state.

In my code I go:

 var State = $("select[name=state1]").val();

So if AZ was selected, the ouput would be State == "AZ"

Then I have arrays for every state so for example:

var AZ =[[1],[2]];

And I fill each array with some data. Then I try to do a calculation that looks like this:

var ABC = 25 * State[0][1];

However, the variable state isn't an array. I want state replaced by the chosen one, for example it might be AZ so I actually want to calculate...

 var ABC = 25 * AZ[0][1];

Any ideas on how I can pass the value of State into last equation automatically?

Upvotes: 0

Views: 71

Answers (2)

J. Titus
J. Titus

Reputation: 9690

I suggest assigning your state values a little differently:

var states = {
    AZ: [[1],[2]],
    //and so on
};

Then you can do

var ABC = 25 * states[State][0][1];

Upvotes: 1

artm
artm

Reputation: 8584

Change your state to be an object to contain state arrays:

var state = { AZ : [[1],[2]], OS : [[3], [4]] };
var abc = 25 * state["AZ"][0]

Upvotes: 1

Related Questions