VK said:
1) You may construct your own Hash object using Object as prototype (the
most academically proper way, but may be boring and time consuming).
2) You may try Enumerator object, but I believe it's full on bugs and IE
only.
3) You may simply imitate enumeration method, something like:
var aStatList = new Object();
aStatList.length = 0;
...
aStatList['key'] = value;
aStatList.length+=1;
The problem with your approach is that:
for (var key in aStatList) {
// key == 'length' will be true at some point through this loop
}
Actually, -key- might also contain other enumerable properties of the Object
object as well.
P.S. And don't expect to have your key/value pairs in the order you put them
there. Hash rearrange pairs in its own internal order, which is for human
perception is a total disorder.
One way to avoid this is to store an array of keys and the actual value as a
property of an object. That way you avoid enumerable objects, and you can
control the order the order objects appear in:
<script type="text/javascript">
function Collection() {
var collection = {};
var order = [];
this.add = function(property, value) {
if (!this.exists(property)) {
collection[property] = value;
order.push(property);
}
}
this.remove = function(property) {
collection[property] = null;
var ii = order.length;
while (ii-- > 0) {
if (order[ii] == property) {
order[ii] = null;
break;
}
}
}
this.toString = function() {
var output = [];
for (var ii = 0; ii < order.length; ++ii) {
if (order[ii] != null) {
output.push(collection[order[ii]]);
}
}
return output;
}
this.getKeys = function() {
var keys = [];
for (var ii = 0; ii < order.length; ++ii) {
if (order[ii] != null) {
keys.push(order[ii]);
}
}
return keys;
}
this.update = function(property, value) {
if (value != null) {
collection[property] = value;
}
var ii = order.length;
while (ii-- > 0) {
if (order[ii] == property) {
order[ii] = null;
order.push(property);
break;
}
}
}
this.exists = function(property) {
return collection[property] != null;
}
}
var myCollection = new Collection();
myCollection.add("first", "Adam");
myCollection.add("second", "Eve");
myCollection.add("third", "Cane");
myCollection.add("fourth", "Abel");
myCollection.remove("second");
myCollection.add("fifth", "Noah");
alert(myCollection.toString());
alert(myCollection.getKeys());
myCollection.update("first");
alert(myCollection.toString());
alert(myCollection.exists("third"));
alert(myCollection.exists("something"));
</script>
Note that this is not a fully-featured (or even that well thought-out)
Collection object. It's just an example of how to store arbitrary key/value
pairs in an ordered list.
An improvement to the design would be to append a randomly generated
prefix/suffix to each -key-, to be sure to avoid conflicts with existing
property/method names.