views:

59

answers:

3

Hi all,

my aim is to compare the first names with the title of an img-element and insert the last name when the first name matches the title of the img-element. But before programming it, I'd like to ask you a question.

Is there an easier way to create a new array list containing the first and the last name than I've chosen? It would be very inconvenient if I had about 100 new Arrays each containing a first and a last name.

 var username = new Array();

  username[0] = new Array();
  username[0]["first name"] = "daniel";
  username[0]["last name"] = "obrian";

  username[1] = new Array();
  username[1]["first name"] = "stuart";
  username[1]["lastname"] = "oconner";

Thank you in advance.

+7  A: 

You're looking for Object literal syntax:

var username = new Array();
username[0] = { "first name": "daniel", "last name": "obrian" };
username[1] = { "first name": "stuart", "last name": "oconner" };

Note that your example creates an array but then assigns properties to it, so it's not really an Array in the correct sense. JavaScript doesn't have associative arrays, but Object maps do the job.

There's also a similar syntax for array literals, where you can specify the values during array initialization:

var username = [
    { "first name": "daniel", "last name": "obrian" },
    { "first name": "stuart", "last name": "oconner" }/*,
    { ... },
    { ... },
    { ... } */
];
Andy E
Thank you. And thanks for pointing out what I was looking for. I'll mark the answer as accepted in about 7 minutes.
Faili
+2  A: 

Your inner arrays should be objects instead:

var username = [
    { first_name: "daniel", last_name: "obrian"},
    { first_name: "stuart", last_name: "oconner"},
    // etc...
];

And I would use first_name instead of "first name" for the keys to simplify the syntax.

Edgar Bonet
A: 

You mean something like this?

var people= [["daniel", "obrian"],["stuart","oconner"]];
alert(people[0][0]);
Ravindra Sane