1

It's super late and my mind is blanking right now, but let's say I have variable filename and it's storing the name of another variable marker. The variable marker is an array and contains the object & property position: new google.maps.LatLng(42.2550,-114.3221).

I've been stupidly trying to access it via filename.position which of course returns undefined, since it's searching the literal filename for a 'position' property that does not exist.

But how could I pull marker.position by using filename? Is there some nifty jQuery trick for, uh, 'resolving' a variable to its contents? I'm brain fried. I know I've done this before.

Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
daveycroqet
  • 2,667
  • 7
  • 35
  • 61
  • 1
    Use bracket notation: `window[filename].postion`, for instance. – apsillers May 14 '13 at 12:35
  • 1
    @apsillers It will work *only* in case if `filename` was defined globally. – VisioN May 14 '13 at 12:35
  • 1
    Duplicate: [Access value of JavaScript variable by name?](http://stackoverflow.com/questions/4399794/access-value-of-javascript-variable-by-name) – apsillers May 14 '13 at 12:35
  • 1
    @VisioN Yes, that's exactly why I said "for instance" -- it's an example of how bracket notation could be used to access a property of `window`. Certainly, a complete answer would explain the larger context of how to avoid globals (e.g., object namespacing), but the syntax would be identical. – apsillers May 14 '13 at 12:36
  • 1
    God, yes, thank you. I'm retarded. – daveycroqet May 14 '13 at 12:39

2 Answers2

2

If it's possible in your script, you can store the data not just in variable, but in a property of some object (usually it's more convenient to use global one). For example

var myObj = {};
myObj.marker = new google.maps.LatLng(42.2550,-114.3221); // or anything else

Then you will be able to get this property using a variable like this:

myObj[filename].position

In this case i would also recomment to check for myObj[filename] existance using typeof structure, just to make sure such property exists in myObj.

if (typeof myObj[filename] !== "undefined") {
  // do something
}

As apsillers noted, you could use global window object for this as well. But if your marker variable was defined inside some other function (i.e. not global), you won't be able to access it with window.marker or window[filename] as it will be out of scope.

Second way is to use eval() function which i'd strongly recommend to avoid.

Devtrix.net
  • 705
  • 7
  • 8
  • Unfortunately, my variable was local inside another function. I then wanted to access it inside a separate jQuery function, so I had to go global with `window`. If I had the foresight, none of that would have been necessary. Not sure how to reconcile it without using globals and I'm unwilling to do a total rewrite for the nonce. Regardless, thanks anyway! – daveycroqet May 14 '13 at 13:59
0

Try this :

window[filename].position;
Ankit Tyagi
  • 2,381
  • 10
  • 19