Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a constructor that makes squares.

I would like my code to automatically create squares from this constructor using loops and name them square1, square2, square3 ect.

eg.

for (n=1; n < x; n++){
var square(n) = new Square();
}

Is this possible?

If so how and how do I refer to them in a loop - like square(n)?

I'm new to programming, oop and javascript so sorry if this is really ovb. thanks in advance

share|improve this question

2 Answers 2

That's what Arrays are for:

var squares = new Array();
for (var n = 1; n < x; n++) {
    squares.push( new Square() );
}

Now you're able to access them with their zero-based index:

squares[0].someMethod(); // etc..

To iterate over all the squares in that array:

for (var i = 0; i < squares.length; i++) {
    squares[i].someMethod();
}
share|improve this answer
1  
You can simply use squares.push(...) to append a new element. –  ThiefMaster Jun 10 '12 at 12:13
    
Yeah right, that's better, thanks! –  Niko Jun 10 '12 at 12:14
    
so squares is an array full of objects that are all called Square each refered to by the array index? –  Steve Booth Jun 10 '12 at 12:57
    
Essentially yes - the objects don't have a name (but an index instead), and they all are instances of the Square constructor. –  Niko Jun 10 '12 at 13:03

That's a pretty nasty idea. Use an array for this purpose:

var squares = [];
for (var n = 1; n < x; n++) {
    squares.push(new Square());
}

Anyway, if you really want to do it:

window['square' + n] = new Square();

This will create globals. There is no clean, eval-less way to create locals like that.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.