[thelist] [javascript] for ... in - prevent certain properties from showing up

Marcus Andersson marcus at bristav.se
Fri Nov 19 11:24:17 CST 2004


Ben Taber wrote:

> function associativeArray() {
>     var length = 0;
>   
>     this.add = function(name, object) {
>         this[name] = object;
>          length++;
>     }
> 
>     this.getLength = function() {
>        return length;
>     }
> }

If you're happy using a functional solution you could do something like this:

function associativeArray() {
   var length = 0;

   this.add = function(name, object) {
     this[name] = object;
     length++;
   }

   this.getLength = function() {
     return length;
   }

   this.forEach = function(fun) {
     for(var i in this) {
       if(typeof(this[i]) != "function") {
         fun(this[i], i);
       }
     }
   }
}

Then you could use it by passing a function (anonymous inline or a function pointer) into forEach that takes 
to arguments.

var arr = new associativeArray();
arr.add("name1", "value1");
arr.add("name2", "value2");

arr.forEach(function(o, name) {
   alert(name + " has value " + o);
});

Another alternative would be to to do something like the following:

function associativeArray() {
   var length = 0;
   var items = new Object();

   this.add = function(name, object) {
     this[name] = object;
     items[name] = object;
     length++;
   }

   this.getItems = function() {
     return items;
   }

   this.getLength = function() {
     return length;
   }
}

and then

var arr = new associativeArray();
arr.add("name1", "value1");
arr.add("name2", "value2");

for(var name in arr.getItems()) {
   alert(name + " has value " + arr[name]);
}

I like the first one better (since I have started to like functional programming lately) but the second 
approach should work as well but there is the annoyance with a double set of references (but it is only 
references to it isn't that bad).

/Marcus


More information about the thelist mailing list