Dynamically creating and naming objects

Hi guys, hope someone can help me with this one…

I’ve got an input with a value. The input is called ‘command2’ and I want to send it’s value to the ‘rover2’ object (although I don’t know if that object exists yet). I test and say if(rover2){… and if not then I create the object/if so then I insert the value.

Question is: I want to do:

var rover2 = new Rover();

but I want to pass the name of the new object by association, so in effect:

var "rover"+i = new Rover();

How would you do that? So that the objects and their names are generated dynamically (or [perhaps a better explanation] so that the string value of a variable can be used as the name of new variable/object)?

Any takers?

Jim :slight_smile:

PS Bonus marks: If I hold HTML fragments as an object and those fragments include inputs, is the value of the input collected as well? i.e. if I have

<fieldset>
<input id="foo" type="text" />
</fieldset>

and onsubmit I capture it and the user has entered a value, is the value still held as document.getElementById(‘foo’).value? And, given that I can’t use .getElementById(‘foo’) on the object, what would be the best way to do extract it (if it’s there, obviously).

Again, many thanks for your consideration. :slight_smile:

@pmw57

Thank you so much for that! I was trying to create it as a local, which as you point out would not be the best way in this circumstance.

Incidentally, how would you declare that locally? I got lots of syntax errors…

It might be possible using eval,


eval('rover' + i + ' = new Rover()');

But that’s horrible, inefficient, and evil.

Have you heard that eval is evil?
http://blogs.msdn.com/b/ericlippert/archive/2003/11/01/53329.aspx

if it’s to be a global variable, you can define rover2 as a global variable with:


var i = 2;
window['rover' + i] = new Rover();

You can then access it with window.rover2 or just rover2, though I would stay with the window.rover2 as a reminder to you that it is supposed to be a global variable.

If instead of being global it’s local to somewhere, similar techniques can be applied too depending on the situation.

A shorter form of the problem is this:


var ids = [],
length = ids.length;
ids[0] = "rover1";
ids[1] = "rover2";

for(i=0; i<length; i+=1){
		ids[i] = new Array();
}


JS will always see ids[i] as a string and name the object(in this case an array) with that string. It will never see it as ‘name the object entry ‘i’ in this array’. Any ideas?

I don’t think that it’s possible to obtain a collection of locally scoped variables so that you can then access and modify them in the same way as you can for those in the global scope.

Instead, you may need to use an array-like syntax, using rover[0], rover[1], rover[2], etc.