0

I want to create multiple object using a class for example:

function _Class(_number) {
     this.numer = _number;
    }

and i want to make 36 objects with the same attributes but different values. I stuck almost on beggining because i used loop :

for (var i = 0; i < 37; i++) {
name="number_"+i;    
var name=new _Class(i); 
}

and after this code i can't acces to any object. Is there a way that I can create a variable which name is value of array ?

All code:

//test 
function test(x){
    for (var i = 0; i < 37; i++) {
        document.write(x);
    }
}
var pola = [0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26, 0];
var nazwy_obiektow = new Array(100);
for (var i = 0; i < 37; i++) {
    nazwy_obiektow[i] = "liczba_" + i;
}
function _Klasa_Liczb() {
     this.numer = 1;
    }
for (var i = 0; i < 37; i++) {
    var nazwy_obiektow[i]=new _Klasa_Liczb; 
}
test(liczba_0);
1
  • Create the variable outside of the loop. To initialize it to an array, the most concise way is like: var myArray = []; Commented Dec 7, 2015 at 14:30

1 Answer 1

4

You could use an array.

function _Class(_number) {
        this.numer = _number;
 }
 var objects = [];
 for (var i = 0; i < 37; i++) {
    name = "number_" + i;
    objects[i] = new _Class(name);
 }

Then you can see each object in the array (objects[0], objects[1],...).

Sign up to request clarification or add additional context in comments.

3 Comments

Done this and I can't acces to the values of object outside the code.
Where is your var objects? Think that the scope of your variables is the function which was declared. Define your objects outside of functions.
@Czcibor if you think this is a right answer to your question, you should mark it as "Answer" so other users know it helped you.

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.