Call Array Dynamically in a function
I have a map of the US w开发者_开发知识库ith 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.
You should store the state arrays in their own object:
var stateData = {
HI: [1, 2, 3],
IL: [4, 5, 6],
...
};
var myData = stateData[state];
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.
In 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);
}
精彩评论