creating javascript objects with unique names depending on counter in loop

I'm new enough to Javascript, and I have a small query about formulating variable names :

function createObjects(int length) {
  var count;
  for(count=0; count<length; count++;) {
    var personObj + "" + count;
  }  
}

here I want to formulate a different personObj for each iteration of the for loop, is this the correct procedure? will this give me : var personObj1 var personObj2 etc

Thanks! Matt

Answers


If you want to have several instances of the same underlying data structure / logic you could use an approach like this:

Create a constructor function that generates an Object with the properties (also methods) that you need. For example:

function PersonObj(name, age) {
    this.name = name;
    this.age = age;
}

This enables you to create a new instance of PersonObj by using var n = new PersonObj('Fred',32);. Now you can use an Array to store multiple instancesof these objects:

var persons = []; // creates a new Array

for (var i = 1; i < 13; i++){
    persons.push(new PersonObj('Alfred', i));
}

persons will now contain twelve Alfreds of age 1 to 12.

If you want to alter Alfred No. 3's age you could do:

persons[2].age = 99;

See a live demo


Don't. Dynamically generating variables is never a good idea. Use an object or an array instead. They are designed to structure groups of related data.

function createObjects(length) {
  var count, people = [];
  for(count=0; count<length; count++;) {
    people.push('something');
  }  
  return people;
}

Why not use an array for this instead?


if needs must, you can alwvays add a named property to the window object:

function createObjects(int length) {
  var count;
  for(count=0; count<length; count++;) {
    window[personObj + "" + count] = new SomeObject();
  }  
}

Create the objects, add properties to objects and store the objects in an array.

var al = new Array();
function createObjects(int length) {
 var o = new Object();
  for(var count=0; count<length; count++;) {
      o.count = 'some value';
  } 
al.push(o);
}

Need Your Help

Sending emails to multiple recipients - best practices

email spam-prevention

My application server needs to notify users about some events via email. Usually there will be between 10-100 users to whom the notifications should be sent, but there may be a few cases where ther...

Batch Programming: Moving Files to Folders Based on Date Modified

batch-file

Thanks for visiting. My question: I receive daily files that are stored as .csv's, typically with the following format: DEVICE_DEVICENumber_DateID. I'd like to move these files into their respective