Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.javascript > #14681
| From | Mike Winter <usenet@michael-winter.me.invalid> |
|---|---|
| Newsgroups | comp.lang.javascript |
| Subject | Re: [Newb] How to reference object by string+var |
| References | <330931e1-5e30-4999-8e90-ee55f5327b77@googlegroups.com> |
| Message-ID | <wKnGr.411390$S84.230615@fx23.am4> (permalink) |
| Organization | virginmedia.com |
| Date | 2012-06-26 20:06 +0100 |
On 26/06/2012 18:21, skoskie wrote:
> I'm trying to reference a google maps object by concatenating a string and a var but see no way of doing so. Super newb to JS. Any help would be greatly appreciated.
>
> URL: example.com?locationID=254
>
> Simplified example of code:
> ========================
> var location = getUrlVar('locationID'); <-- Works!
> markerInfo.open( 'marker'+location );
> ========================
>
> So you can see that "marker254" is an object I need to pass reference to. I've tried to use eval(), but it didn't work for me and from what I've read it's not the most secure approach anyway.
Hi,
In what scope is the object, marker254? If it can be accessed as a
property of some object ('container' below) then you can construct a
property name using bracket notation:
container['marker' + location]
If it's a global variable then it can be accessed as a property of the
window object or an equivalent reference. If it's a local variable this
is more tricky and you'd be better off assigning it as a property of
some plain object that you'd then use like a map. Without knowing more
about your existing code, I can't provide anything more than a contrived
example to demonstrate this:
var markers = {};
// ...
markers.marker254 = new Marker(); // or simply markers[254] ?
// ...
markerInfo.open(markers['marker' + location]);
Hope that helps,
Mike
--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
[Newb] How to reference object by string+var skoskie <smkoskie@gmail.com> - 2012-06-26 10:21 -0700
Re: [Newb] How to reference object by string+var Mike Winter <usenet@michael-winter.me.invalid> - 2012-06-26 20:06 +0100
Re: [Newb] How to reference object by string+var skoskie <smkoskie@gmail.com> - 2012-06-26 13:40 -0700
csiph-web