0

I am trying to access an object but the name is variable. So: I have object41, object42 and object43. I want to access object42.

id = 42;

something like this:

object+id.function();

I have searched and found how to assign objects with variable names and how to access properties with variable names but I can't figure out how to access objects with variable names.

Is this something obvious that I am missing?

tgurske
  • 35
  • 5
  • 1
    Try for `object[id].function()`. If you have at least `42` related objects, use an object to organize them, rather than as dispersed variables. Related: [Javascript dynamic variable name](http://stackoverflow.com/questions/5117127/javascript-dynamic-variable-name) – Jonathan Lonowski Aug 24 '14 at 22:02
  • 1
    Why not using like this [jsBin](http://jsbin.com/pexahagatiko/1/edit?html,js,output) – hex494D49 Aug 24 '14 at 22:29

2 Answers2

2

If these objects are global, you can access them via the window object, and then call your function on the resulting object.

var id = 42;

window["object" + id].function();
jstricker
  • 2,132
  • 1
  • 30
  • 44
  • 1
    @elclanrs I wouldn't personally write my code this way, but this is still the answer to the actual question asked. – jstricker Aug 24 '14 at 22:02
  • Didn't work for me: TypeError: window[("object" + id)] is undefined. – tgurske Aug 24 '14 at 22:09
  • If I hard code it like: object42.function();, it works fine. So, I assumed the scope was ok. – tgurske Aug 24 '14 at 22:12
  • @tgurske How do you have your variable `object` defined? What I suggested will only work if it is a global. – jstricker Aug 24 '14 at 22:18
  • marker42 = new google.maps.Marker({ position: markerPos42,map:map}); – tgurske Aug 24 '14 at 22:22
  • @tgurske Check it out in the debugger. `object42`, `window.object42`, `window["object42"]`, and `window["object" + 42]` should all resolve to the same thing. – jstricker Aug 24 '14 at 22:29
0

Try using eval

// Sample object
function X(id) {
    this.value1 = "A" + id;
    this.function = function f(value){
        alert(value);
    };

   return this;
}

// n number of object created
var object1 = new X(1);
var object2 = new X(2);

// iterate over all object
for (i=1; i<=2; i++) {
    var expr = "object"+i+".function(object"+i+".value1)";
    eval(expr);    
}

Here a jsfiddle : demo

QIKHAN
  • 274
  • 2
  • 4