1

I've created empty array like this:

var cars = [];

And I'm going to add every car's name and cost. For instance:

car[0]["name"] = "BMW";
car[0]["cost"] = 50000;

But the problem is, we don't know which index is array dealing with (whether it is 0, 1, 2, 3, 4 ??). Every time I should declare new multidimensional array like this:

car[] = [];

And add two values to it ("name" and "cost") without knowing which index it has. Appreciate any help guys. If my question looks like ridiculous, sorry for that.

2
  • 3
    car.push({name:"BMW", cost:50000}) Commented Dec 9, 2016 at 5:15
  • car[] = {name:"BMW", cost:50000}; Commented Dec 9, 2016 at 5:17

3 Answers 3

4

You can use Array#push method to insert Objects instead of creating multidimensional array

var cars = [];
//insert elements like

cars.push({name:"BMW", cost:50000});
cars.push({name:"Ferrari", cost:55000});
// see the cars
console.log(cars)

Sign up to request clarification or add additional context in comments.

Comments

1

It looks like you're wanting to store an array of objects? Like so:

[{ name: "BMW", cost: "55222"}, { name: "Toyota", cost: "25222" }]

This way you could start off with an empty array and then just push objects to it:

var carsArray = []
carsArray.push({ name: "BMW", cost: "55222"}) // Push the BMW to the array
carsArray.push({ name: "Toyota", cost: "25222"}) // Push the Toyota to the array
console.log (carsArray) // This will contain two cars

Comments

0

Generally speaking to deal with arrays you either populate or retrieve Values, what i understood is that you wanna know the index so here's a small example:

 var cars = [];

for population:

 cars.push({name:"BMW", cost:50000}); /*Where {name:"BMW", cost:50000} is a new object 
and you can populate it with any parameters and any values*/

for value retrieval:

for(var i=0;i<cars.length;i++){
   console.log(i);//Here is the index
   console.log(cars[i]);//Here is the value
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.