Close Circle Icon
This forum is now read-only. Please use our new forums at discuss.codecademy.com.
0 points
Submitted by Mark Hempel
8 years ago

Using a loop to create objects

I used a loop to create an array of the variable names:

title = [];
for (var i=1; i<4; i++){
title.push(“object”+i);

} //console.log(title)

I tried to use another loop to take each element out and create an object:

for (var i=0; i<title.length+1; i++){
var title[i] = new object(); }

Is there a perfered method for this proceedure? can you use string values to define variables in a loop similar to my attempt?

Answer 515b7f1cac9f443253000354

0 votes

Permalink

Why break the process into two loops when it can be handled all together:

var title = [];
for (var i=0; i<3; i++) {
    title[i] = {
        name: "name" + i+1,
        age: "age" + i+1,
        hometown: "hometown" + i+1
    };
}
console.log(title);
// output will be:
// [ { name: 'name1', age: 'age1', hometown: 'hometown1' },
//   { name: 'name2', age: 'age2', hometown: 'hometown2' },
//   { name: 'name3', age: 'age3', hometown: 'hometown3' } ]
834 points
Submitted by Eric Smith
7 years ago