CodeOrc.com - Learn by example
X
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);
DO IT
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);
DO IT

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>"); }
DO IT

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>"); }
DO IT

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>"); }
DO IT

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

Set

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 ); }
DO IT

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 );
DO IT

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
<< >>
X