wwfarch
asked on
Dynamic Variable Names
I'm quite new to javascript (writing my first app actually). My hope is to dynamically generate a map using google maps based on data read from a file. I need the ability to add/remove overlays etc... That's just a bit of overview.
Specifically what I need to do is create variable names dynamically. I have a function as decrlared below
function func1(id, x, y)
I want the body of the function to be able to do something like
var object<id> = new GLatLng(x,y);
I currently have window["object" + id] = new GLatLng(x,y);
However, I can't figure out how to reference window["object" + id] again. I need to reference this variable in the same function and in other functions as well.
I have considered using a global array (probably will for now) but I'm not sure that this is efficient since the ids may be sparse and very large. As I said I know next to nothing about javascript so any ideas are welcome.
Specifically what I need to do is create variable names dynamically. I have a function as decrlared below
function func1(id, x, y)
I want the body of the function to be able to do something like
var object<id> = new GLatLng(x,y);
I currently have window["object" + id] = new GLatLng(x,y);
However, I can't figure out how to reference window["object" + id] again. I need to reference this variable in the same function and in other functions as well.
I have considered using a global array (probably will for now) but I'm not sure that this is efficient since the ids may be sparse and very large. As I said I know next to nothing about javascript so any ideas are welcome.
no need eval, just call object1, object2
but if you want use it global do not put "var" inside of the function, beacause it will be local variable.
but if you want use it global do not put "var" inside of the function, beacause it will be local variable.
ASKER
The problem with referencing it as object1, object2, etc... is that I have no idea what the id will be at any time during the program so i can't hardcode any names like that. I think the eval approach would work but can I also use eval to reference the variable later (assuming it's global)?
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
eval('object'+id+' = new GLatLng(x,y)');
Then simply reference it like this:
object1, object2, object3...