user5775744 user5775744 - 6 months ago 7
Javascript Question

How could I iterate with a for loop to create many objects with Object.create on the fly in javascript?

I am trying to create a function that will dynamically create objects on the fly based on the input number arguments, but I'm running into an issue with iterating over the Object.create() part. I don't know where to play my i in the for loop, but ideally I would have all the sportsCar objects stored in the sportArray. That is the target at least.

function car(doors, capacity, storage) {
this.doors = doors;
this.capacity = capacity;
this.storage = storage;
};


var van = Object.create(car);
van.doors = 4;
van.storage = "rear storage";

var miniVan = Object.create(van);
miniVan.capacity = "200 LB";

var cargoVan = Object.create(van);
cargoVan.capacity = "800 LB";

var truck = Object.create(car);
truck.doors = 2;
truck.storage = "bed";
truck.capacity = "1500 LB";

var familyCar = Object.create(car);
familyCar.doors = 4;
familyCar.storage = "large trunk";
familyCar.capacity = "300 LB";

var sportsCar = Object.create(car);
sportsCar.doors = 2;
sportsCar.storage = "small trunk";
sportsCar.capacity = '100 LB';

function tally(n1, n2, n3, n4, n5) {
var sportArray = [];
var familyArray = [];
var truckArray = [];
var miniArray = [];
var cargoArray = [];

sportsObjs = for(var i = 0; i < n1; i++){
Object.create(sportsCar);
}

sportArray.push(sportsObjs);

for (var i = 0; i < n2; i++){
Object.create(familyCar);
}

for(var i = 0; i < n3; i++){
Object.create(truck)
}

for(var i = 0; i < n4; i++){
Object.create(miniVan)
}

for(var i = 0; i < n5; i++){
Object.create(cargoVan)
}

return console.log(sportsArray);

}

Answer
sportsObjs = for(var i = 0; i < n1; i++){
   Object.create(sportsCar);
}

sportArray.push(sportsObjs);

That's a plain syntax error. A loop is a statement in JavaScript, not an expression - it doesn't yield a value. You can't assign it to a variable. What you actually want is to assign each newly created object to the variable, and then push that particular new object to the array:

for (var i = 0; i < n1; i++){
    var sportsObj = Object.create(sportsCar);
    sportArray.push(sportsObj);
}