<wl*****@sigsys.netwrote in message
news:11**********************@75g2000cwc.googlegro ups.com...
Can someone give me an example of how to construct an array of objects?
for example, I have:
function objFacility(id,name,adr,city,state,zip)
{
this.id = id
this.name=name
this.adr=adr
this.city=city
this.state=state
this.zip=zip
}
I would need to search the array by id then access one element
Assuming you want an arrau of those objects: ;^)
You can do this in literal notation like so:
MyArray = [
new objFacility(...),
new objFacility(...),
new objFacility(...)
];
The brackets indicate an array.
You can also do this in script like so:
MyArray = new Array();
MyArray[MyArray.length] = new objFacility(...);
In this case "MyArray.length" is just saying "make this the last element in
the array". You could also, of course, loop over something to do the same
thing:
Just as a plug. If you need to do any really work with the resulting array
of objects you might want to check out my Object Collection Ordered
abstraction object here:
http://www.depressedpress.com/Conten...ered/Index.cfm
It basically creates an array of objects as we've just done but also exposes
lots of methods for managing and ordering them. Once the object is imported
you might do this:
MyFacilities = new DP_ObCollectionOrdered("id", objFacility);
This creates the collection and tells it that only "objFacility" objects can
be stored in it. It also tells it that the "id" field will be used as the
unique identifier for the collection.
You can then add elements to the collection like this:
MyFacilities.add( new objFacility(...) );
MyFacilities.add( new objFacility(...) );
MyFacilities.add( new objFacility(...) );
Once that's done you have a lot of capabilities. To get one element you
would just do:
MyFacilities.get(FacilityID);
To get everything (as a reference to the internal array) you would do:
MyFacilities.getAll();
To get the first element in the collection you would say:
MyFacilities.getAt(0);
To move the first element down two steps (in the language of the collection
object "reduce its rank by two") you would do:
MyFacilities.demoteAt(0, 2);
To move a specific element down two steps you would say:
MyFacilities.demote(FacilityID, 2);
There are lots of similar methods for adjusting rank: promote(),
promoteAt(), swap(), swapAt(), setRank(), etc.
Finally the collection object offers a generic, but pretty powerful sorting
function called "sortByProp()". To sort the collection by Facility Name
regardless of alphabetic case you could do this:
MyFacilities.sortByProp(name, "AlphaNoCase", "asc");
To resort the list by name descending you would just do this:
MyFacilities.sortByProp(name, "AlphaNoCase", "Desc");
There are examples on the page for generating drop down select boxes and
dynamically sortable tables on the page as well.
I hope this helps,
Jim Davis