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);
}
2 Answers 2
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;
}
6 Comments
postvalues? Is it an array?for loop rather than a for-in loop. This also allows you to use the loop index to generate the <div> IDs.<div> IDs are not make1, make2, etc., they are something else. Can you post the HTML you are working with?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
8 Comments
cars = [].cars.push(car1, car2, ...)
[]? E.g.cars.push(car[0], car[1], car[2], car[3]);document.getElementByIdare going to come back the same for each iteration of the for-loop. Is that intentional?Car1, ... in that piece of code? That (broken) code seems unrelated to your question. Not clear, at least to me.var car.concat(n)will declare a variable namedcar1whenn = 1.