Night
Night

Reputation: 749

Possible to name different arrays within a multi array?

I wondered if it were possible to name arrays within a mutli array, as I know you can do, for example:

var cars = new Array();
cars[0] = "Saab";
cars[1] = "Volvo";
cars[2] = "BMW";

I wondered if it would be possible to some how do:

var cars = new Array();
cars[Saab] = "9-3 Aero";
cars[Volo] = "S80";
cars[BMW] = "I8";

If not, its all good - just wondered if anyone had a way of doing this.

Upvotes: 0

Views: 60

Answers (3)

Michel
Michel

Reputation: 4157

You also can do:

var cars = new Array();
cars[0]['brand'] = "Saab";
cars[1]['brand'] = "Volvo";
cars[2]['brand'] = "BMW";

cars[0]['type'] = "9-3 Aero";
cars[1]['type'] = "S80";
cars[2]['type'] = "I8";

Upvotes: 0

WebServer
WebServer

Reputation: 1396

javascript objects are named array!!!!!

var cars = {};
cars["Saab"] = "9-3 Aero";
cars["Volo"] = "S80";
cars["BMW"] = "I8";

Upvotes: 1

georg
georg

Reputation: 215009

The correct syntax is

var cars = {};
cars.Saab = "9-3 Aero";
cars.Volvo = "S80";
cars.BMW = "I8";

or

var cars = {
   Saab:  "9-3 Aero",
   Volvo: "S80",
   BMW:   "I8"
}

This is called an object literal.

Upvotes: 4

Related Questions