milov.nl

Interaction design • webdevelopment • web art • photography

May 2005

Sets in Javascript [via]



Mathieu 'P01' HENRI wrote on 2005/05/12:
o_O I didn't knew the in statement could be used outside of a "for( iterator in object )"


Milo wrote on 2005/05/12:
Now that I think about it, unless I'm missing something, one could also simply use:

var TypeInSet = nodeType in [2, 3, 4, 7, 8];

...thus bypassing the need for the custom set() function.


Milo wrote on 2005/05/12:
Oh wait, I am indeed missing something :)
in checks the *index*, not the values, so my idea makes no sense at all.


Mathieu 'P01' HENRI wrote on 2005/05/12:
:)
It's not exactly the indexes. It's the name of the properties ( member variables ) of the object.


Milo wrote on 2005/05/12:
True... but with regard to arrays I always think of those as 'string-based indexes' ;)

Anyway, to make something that *does* work for array literals, I came up with this:

Array.prototype.contains = function(n)
{
for (var i in this)
{
if (this[i] == n) { return true; }
}
return false;
}

var typeInSet = [2, 3, 4, 7, 8].contains( nodeType );