Reputation: 5840
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.
Upvotes: 1
Views: 1254
Reputation: 177
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
}
Upvotes: 0
Reputation: 15903
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
Upvotes: 1
Reputation: 115212
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)
Upvotes: 4