2

Say I already have many objects, like obj1, obj2, .....obj30.....

Now I am trying to write a function like this:

function blar(N){
 do something to objN
} 
blar('4');

So far it seems that the only way to do it is

function blar(thisObj){
 do something to thisObj
}
blar(obj4);

I wonder what is the right way to pass the N such that the function can use that N value to process objN.

Hope I make myself clear.

PS: I even try something like blar(obj+N) but apparently it's wrong too, as the system tries to find obj, which doesn't exist.

1
  • Object... Number. Let me try that again: Object, Number... Commented Jun 7, 2011 at 6:36

3 Answers 3

2

Use square bracket notation.

window['obj' + N];

This depends on them dangling off the window object and not being nicely scoped though.

… but if you have a bunch of objects, which are identified by being the same except for a number, then you should probably be storing them in an array in the first place. Then you would just:

myArray[N];
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, why I never think of array. Thanks for the great tip!
0

Use eval:

function blar(N) {
    var obj = eval("obj"+N);
}

Or, if you can put those objects into an object, you can use []

function blar(N) {
    var obj = tracker["obj" + N];
}

Comments

0

It's pretty simple:

function blar(objectNo) {
  var obj = eval('obj' + objectNo);
  alert(obj);
}

To give you some keywords for talking with others about this: what you want to do is to access an object by its name, in the current scope.

But note that the following doesn't work:

function main() {
  var a = 1, b = 2, c = 3;

  blar('a'); // doesn't work
  doSomething(eval('a')); // works
}

This is because the variable a is only visible in the main function, but not in blar. That is, the eval must be called in a scope where the variable is visible.

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.