1

I am having trouble understanding how arrays work in javascript.

Lets say I have an object, car

car = {
moving: false,
wheels: 4
};

Lets say I want to create an array now, of 5 of these cars. How would you do that? I would want to use a for loop to create them, but I have read many pages on js arrays such as http://www.w3schools.com/js/js_arrays.asp and I am still stumped.

I tried doing

carArray = [];
for(int i=0; i < 5; i++)
{
carArray.push(car);
}

However, when the program runs, there is only one car, not 5, and it is at the last entry of carArray.

qwerty54
  • 21
  • 4

1 Answers1

0

The word int should be removed. Then the code should work.

carArray = [];
for (i = 0; i < 5; i++) {
  car = {
    moving: false,
    wheels: 4
  };
  carArray.push(car);
}
Ian Hazzard
  • 7,661
  • 7
  • 34
  • 60