0

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.

1
  • to achieve something like that you would need to create an object with the properties as the cars and their values as the strings you assigned. That way you can access them by name since javascript stores properties of objects as key-value pairs. Commented Dec 30, 2013 at 13:33

3 Answers 3

4

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.

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

Comments

1

javascript objects are named array!!!!!

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

4 Comments

@AkshayKhandelwal : object name as number??????? FYI its returned value from objects toString function or direct literal.
@WebServer: What AkshayKhandelwal said is true. As long as you provide object name as number, JavaScript will keep incrementing the array's length property. The moment you add a string as object name, it's length property will stop incrementing.
@AnupVasudeva: first tell me what do you mean by object name?? and the tell me what will cars[{toString:function(){return "abc"}}] = 100 statement do, and read my previous comment.
@WebServer: Ah, thanks for pointing.. It should be property name instead of object name.
0

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";

1 Comment

In that case, your cars (in the first section) wont be an array.Try outputting cars.length and you'll get 0.

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.