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

Ben Taber ben.taber at gmail.com
Thu Nov 18 18:15:38 CST 2004


This all stems from wanting to be able to get the .length of an
associative array.  For some reason that really makes no sense to me,
associative arrays return .length as 0, no matter how many elements
are in that array.

My initial thought was something like this

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

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

var myAssociativeArray = new associativeArray();
myAssociativeArray.add(myObject);

var length = myAssociativeArray.getLength();

This works dandy.  However, as soon as try to loop through my
associative array... yeah, you know what happens, I get these two
other array elements (add and getLength).  This all makes sense and is
expected behavior, but I would love some way of not getting those
function names in the for...in loop.

I know I could do something like

for ( a in myAssociativeArray) {

   if ( a.typeOf != "function") {

    ..........
    }  

}


but I don't want to do that.  Anybody have any clever ways of working
around this?


More information about the thelist mailing list