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.

3
  • 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). Commented Jun 11, 2017 at 2: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). Commented Jun 11, 2017 at 2: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". Commented Jun 11, 2017 at 3:13

2 Answers 2

6

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>
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.