Dictionaries
Dictionaries are a different kind of collection from arrays. The main difference is that whereas arrays contain individual elements, dictionaries contain key-value pairs. Let’s take a look at some code which creates a JS++ dictionary. Before you write the new code, delete the code you already have in Collections.jspp. Now write in the following:
import System; Dictionary<int> friendsAges = {"Anna": 47, "Betty": 28, "Chris": 35, "David": 54};
On the first line, you import the System
module. We won’t cover modules in detail until the next chapter, but for now the key point is that this import statement lets you use the Dictionary<T>
class, which is in the JS++ Standard Library. (We will cover the JS++ Standard Library in chapter 13.) Without the import statement, the code that comes after would not compile.
With the import statement in place, however, your code does compile and it creates a dictionary that stores friends’ names and their ages in a key-value format. For each key-value pair, the key is the person’s name and the value is their age. The dictionary’s type is Dictionary<int>
, since the value in each key-value pair is an int
. We don’t need to specify the key type, in addition to the value type, since the key type in any dictionary must always be string
.
Note: When writing the keys for a JS++ dictionary, it’s optional to use quotation marks. So for example, instead of writing Dictionary<int> dict = {"a": 1};
you could also write Dictionary<int> dict = {a: 1};
The compiler knows that your keys must be strings, so the quotation marks will be implicitly assumed if you leave them out.
A dictionary’s key-value pairs are not ordered and they are not assigned an index. To access a particular pair, you use its key. For example, if we wanted to display Anna’s age and Chris’s age in our HTML document, we could do so like this:
import System; external $; Dictionary<int> friendsAges = {"Anna": 47, "Betty": 28, "Chris": 35, "David": 54}; $("#content").append(friendsAges["Anna"], " ", friendsAges["Chris"]);
The expression friendsAges["Anna"]
returns the value corresponding to “Anna”, and the expression friendsAges["Chris"]
returns the value corresponding to “Chris”. So if you compile this code and open Collections.html in a browser, your document will display “47 35”.
You can also use a key to change the value of a key-value pair:
friendsAges["Anna"] = 48;
This changes the value corresponding to “Anna” to 48. It doesn’t insert a new key-value pair into friendsAges
, because a dictionary cannot have two pairs with the same key. To insert a new pair into the dictionary, you would have to use a different key:
friendsAges["Emily"] = 39;
JS++ | Collections
In the course of a writing a computer program, you will often need to group multiple elements together into a collection of some form. JS++ provides two sorts of collections to help you in these contexts: arrays and dictionaries. They will be the focus of this tutorial.