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?

2
  • 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 Commented Aug 24, 2014 at 22:02
  • 1
    Why not using like this jsBin Commented Aug 24, 2014 at 22:29

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

6 Comments

@elclanrs I wouldn't personally write my code this way, but this is still the answer to the actual question asked.
Didn't work for me: TypeError: window[("object" + id)] is undefined.
If I hard code it like: object42.function();, it works fine. So, I assumed the scope was ok.
@tgurske How do you have your variable object defined? What I suggested will only work if it is a global.
marker42 = new google.maps.Marker({ position: markerPos42,map:map});
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.