Click to See Complete Forum and Search --> : javascript sets?


tniedoba
11-04-2003, 01:39 PM
Instead of looping through an array to find an element, is it possible to create a set in JavaScript?

I wanna be able to do something like this:

myset = ('10','20','abc','hi')
...
if (curVar In myset) {dosomething}

is this possible in JavaScript... couldn't find it using search.

Thanks in advance.

Tom

Charles
11-04-2003, 02:28 PM
Just use an Object literal to create an associative Array of Booleans a la a Perl hash.

<script type="text/javascript">
<!--
mySet = {10:1, 20:1,abc:1, hi:1}
alert(Boolean (mySet[20]))
// -->
</script>

tniedoba
11-04-2003, 03:38 PM
I modified it slightly to the following, works great!

mySet = {10:1, 20:1, 30:1};

if (!mySet[30]) {alert("not in set!");}

Thanks!

tniedoba
11-04-2003, 04:24 PM
With the above code working, I'm having a problem accessing the data in the set...


How would i return the 1st element in the set?
if I was looping using x, how could i get the x'th item?

tniedoba
11-04-2003, 05:51 PM
For those interested, the solution is as follows:

for (var myItem in mySet)
alert(myItem); //this gives the 1st value of each pair
alert(mySet[myItem]); //gives the 2nd value

Unfortunately it seems that the .length property is not used in associated arrays as far as I know, but so far I have not needed it.