开发者

Is there a 'shorter' way to define a list of e.g. 100 new arrays?

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]["firs开发者_StackOverflow社区t name"] = "daniel";
  username[0]["last name"] = "obrian";

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

Thank you in advance.


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" }/*,
    { ... },
    { ... },
    { ... } */
];


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.


You mean something like this?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜