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.
-
Object... Number. Let me try that again: Object, Number...Jhourlad Estrella– Jhourlad Estrella2011年06月07日 06:36:55 +00:00Commented Jun 7, 2011 at 6:36
3 Answers 3
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];
1 Comment
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
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.