1

I'd like to be able to push values into the associative array below.

var car = [];
car [0] = {type: "audi", age: "10"};
car [1] = {type: "bmw", age: "6"};
car [2] = {type: "tesla", age: "2"};

The method I've tried using to push is the following. Using car.length to push it into the next line of our car array, as it'll always be one higher. I don't know if that's good practice, but I guess it works.

value1 = "hyundai"
value2 = "14";

car[car.length].push({type: value1, age: value2});

I absolutely cannot get this to work, and at this point, as a beginner JS'er, I'm out of ideas.

Reach22
  • 33
  • 1
  • 7
  • 2
    You are using both `[]` and `push` where only one is needed (either use: `car[car.length] = {type: value1, age: value2};` or `car.push({type: value1, age: value2});`, the latter is better). – ibrahim mahrir Jun 11 '17 at 02:47
  • Someone has to point out that javascript does not have associative arrays. Arrays in javascript always has a number index. And while I'm being a pedant (most of the time), having a array of "cars" and naming it car (in singular) irks me a bit (bad semantics). – ippi Jun 11 '17 at 02:53
  • I would start off by learning about the basic data types in JS and what they are called. JS has no "associative arrays". What you are dealing with is an "array". –  Jun 11 '17 at 03:13

2 Answers2

5

The issue with your code is that you were not calling push on a valid object. Please try this code:

<script>
var car = [];
car [0] = {type: "audi", age: "10"};
car [1] = {type: "bmw", age: "6"};
car [2] = {type: "tesla", age: "2"};

console.log(car);

value1 = "hyundai"
value2 = "14";

car.push({type: value1, age: value2});

console.log(car);
</script>
Ravi Gehlot
  • 1,099
  • 11
  • 17
2

you can just car.push({type: value1, age: value2});

user 13
  • 134
  • 8