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.
-
If you ever ask yourself "Should I use eval?", the answer is usually "No.". If you ever ask yourself "Should I use the global window?", the answer is usually "No.". ;o)user113716– user1137162011年06月23日 02:24:01 +00:00Commented Jun 23, 2011 at 2:24
3 Answers 3
You should store the state arrays in their own object:
var stateData = {
HI: [1, 2, 3],
IL: [4, 5, 6],
...
};
var myData = stateData[state];
Comments
Using window is an option, like this:
window[state + "dat"] will get you the array.
But I would suggest ... exactly what SLaks just posted, so do that instead.
6 Comments
.something and ['something'], which is useful in certain situations..something and ['something']. i say it's bad practice cause you'd be creating a bunch of global vars and accessing them dynamically (basically doing eval) instead of putting it neatly in one arrayIn JavaScript, global vars are members of the window object, so you can use the array indexing syntax to get at them without using eval, which is generally to be avoided, like so:
function stateSelect(state) {
var display_data1 = window[state + "dat"];
alert(display_data1);
}