Entry
How do I create an Array of Objects?
How do I create an Array of Objects?
Mar 4th, 2000 20:47
Martin Honnen,
Not different then you create other Arrays (see
http://www.faqts.com/knowledge-base/view.phtml/aid/1529/fid/144/lang/en
)
You create your Array and pass the Array elements (in this case
objects) in
var a = new Array (new Object(), new Object(), new Object());
or you create the Array
var a = new Array();
and then add the elements
a[0] = new Object(); a[1] = new Object(); a[2] = new Object();
The most elegant way is using Array and Object literals (JavaScript1.2):
var persons =
[ {name: 'James Kibo Parry', home: 'http://www.kibo.com'},
{name: 'Nathan Wallace', home: 'http://www.faqts.com'},
{name: 'Marthin Honnen', home: 'http://javascript.faqtsc.com'}
];
which defines an array persons of 3 objects which each have a name and
a home property.
So
alert(persons[0].home)
shows you that ultimate internet home page.
Of course for more complex objects (or for JavaScript1.1) compliance
you first define an object constructor e.g.
function Person (name, home) {
this.name = name;
this.home = home;
}
and then can use that to construct Person objects and add them to an
Array object:
var persons =
new Array (new Person ('James Kibo Parry', 'http://www.kibo.com'),
new Person ('Nathan Wallace', 'http://www.faqts.com')
);
Referencing elements is the same as above so
alert(persons[1].home)
shows you the address you are at.