Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Array Dynamically in a function

I have a map of the US with all 50 states as clickable buttons, when the user clicks a state I want to display information about that state, calling on that state's array dynamically. Below is my own weak attempt that obviously does not work.

var stateList = new Array("AK","AL","AR","AZ","CA","CO","CT","DC","DC2","DE","FL","GA","GU","HI","IA","ID",
        "IL","IN","KS","KY","LA","MA","MD","ME","MH","MI","MN","MO","MS","MT","NC","ND","NE","NH","NJ","NM","NV","NY",
        "OH","OK","OR","PA","PR","RI","SC","SD","TN","TX","UT","VA","VT","WA","WI","WV","WY");

function listenerForI( i ) {
    document.getElementById(stateList[i])
    .addEventListener('mousedown', function() {
        stateSelect(stateList[i]);
    }, false);
}

for (var i = 0; i < stateList.length; i++) {
   listenerForI( i );
}

var HIdat = new Array(20,28,50,2) //one array for all 50 states COdat, AKdat, etc.

function stateSelect(state){
    var display_data1 = state + "dat[0]";
    alert(display_data1);
}

Should I use eval()? I've heard of something you can do with a global "window[]" but I don't understand how that would work.

like image 364
Stephen Avatar asked Sep 24 '26 15:09

Stephen


1 Answers

You should store the state arrays in their own object:

var stateData = {
    HI: [1, 2, 3],
    IL: [4, 5, 6],
    ...
};

var myData = stateData[state];
like image 188
SLaks Avatar answered Sep 26 '26 04:09

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!