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
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
Objectwith the properties (also methods) that you need. For example:This enables you to create a new instance of
PersonObjby usingvar n = new PersonObj('Fred',32);. Now you can use an Array to store multiple instancesof these objects:personswill now contain twelve Alfreds of age 1 to 12.If you want to alter Alfred No. 3’s age you could do:
See a live demo