/    Sign up×
Community /Pin to ProfileBookmark

javascript sets?

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

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@CharlesNov 04.2003 — [font=georgia]Just use an Object literal to create an associative Array of Booleans [i]a la[/i] a Perl hash.[/font]

[font=monospace]<script type="text/javascript">

<!--

mySet = {10:1, 20:1,abc:1, hi:1}

alert(Boolean (mySet[20]))

// -->

</script>[/font]
Copy linkTweet thisAlerts:
@tniedobaauthorNov 04.2003 — I modified it slightly to the following, works great!

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

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

Thanks!
Copy linkTweet thisAlerts:
@tniedobaauthorNov 04.2003 — 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?
Copy linkTweet thisAlerts:
@tniedobaauthorNov 04.2003 — 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.
×

Success!

Help @tniedoba spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...