- Learn by example
Make an RPG
Vue Implementations

Examples of how to use Maps and Sets

Maps hold key/value pairs, kinda like array. Try the following example:

var player = new Map(); player.set("HP", 5); player.set("name", "Gordon"); var hp = player.get("HP"); log(hp);
Try adding our own key/value pairs.

As you can see, you use the map to set keys and values in pairs. This lets you later access that variable using the get function.

You can also do this:

var k = player.keys(); var v = player.values(); log(k); log(v);

When you execute the above, what shows up?

It's not the actual values, but the Iterator object. In order to display it, you need to iterate it. For example:

for( let element of player) { log( element + "<br>"); }

Now you can see both keys and values being iterated through.

This is a for of loop. NOT a for in. If you use in with maps, it's not going to work.

Now let's separate the keys from the values so it's a little easier to access them:

for( let [key, value] of player) { log( key + " : " + value + "<br>"); }

And now, let's only iterate through the keys, and then only iterate through the values:

for( let element of player.keys()) { log( element + "<br>"); } for( let element of player.values()) { log( element + "<br>"); }

Go ahead and player around with the examples a bit and see what you can do with them.


Sets are used to store unique values. This means, you can add the same value several times and it'll only be in there once. Watch this:

var band = new Set(); band.add("Trumpet"); band.add("Horn"); band.add("Trumpet"); for( let instrument of band ) { log( instrument ); }

Notice that Trumpet only appears in there once, not twice, even though we tried to add it twice.

Let's check if the Horn is in the band. And, let's check the size of the band.

var have = band.has("Horn"); log( have ); var size = band.size; log( size );

Well, that's a wrap. Go ahead and share this content, if you liked it:

In the next lesson, we will learn about Examples of how to use Getters and Setters

Get the Latest Tutorial Updates
<< >>