Reputation: 689
I am trying to get out of this, variables Car1 Car2, Car3, Car4 to be pushed to an array. But I can't seem to figure out how to increment a variable within a for loop. Any ideas?
function get_info() {
n = 0;
for (var option_post in postvalues) {
n++;
var pair = postvalues[option_post];
var string_pair = pair.concat(": ")
var new_postvalues = (string_pair.concat(document.getElementsByName(pair)[0].value));
//Set up cars
var make.concat(n) = document.getElementById("make").value;
var year.concat(n) = document.getElementById("year").value;
var model.concat(n) = document.getElementById("model").value;
var car.concat(n) = "Make: ".concat(make.concat(n)).concat("-Model: ").concat(model.concat(n)).concat("-Year:").concat(year.concat(n)); // combine
}
cars.push(car1, car2, car3, car4);
}
Upvotes: 0
Views: 76
Reputation: 15240
There is no reason to create a new identifier on each loop iteration, especially since you are looking to collect the values into an array.
function get_info() {
var cars = [], car;
for (var i = 0; i < postvalues.length; i++) {
// ...
// create a car
car = "Make: " + document.getElementById('make' + i).value
+ "-Model: " + document.getElementById('model' + i).value
+ "-Year: " + document.getElementById('year' + i).value;
// append it to the end of your array
cars.push(car);
}
return cars;
}
Upvotes: 2
Reputation: 207
I would create an object for each car, and then store them in another object keyed by the car name. Something along these lines:
var cars = {};
for(var i = 0; i < carData.length; i++) {
var carRef = "car" + n;
cars[carRef] = {};
cars[carRef].make = carData[i].make;
cars[carRef].year = carData[i].year;
cars[carRef].model = carData[i].model;
}
It's not an exact match to your code, but hopefully you can get the idea from this example. With this, you would retrieve an individual car like this:
cars["car1"]
Or an individual property for a given car:
cars["car1"].make
Upvotes: 0