Dictionaries
A dictionary is another data container, just like an array. But unlike arrays, which store data in a certain order, dictionaries store data using a key-value pair. Instead of associating each element with a predetermined number, like in an array, we associate them with a key that we define ourselves. Because we must define our own keys, there is a more rigid structure in a dictionary than in an array.
Creating a dictionary
Let’s say that we want to store the name, price, and weight of an item in our game. We can do this using a dictionary:
var item = { "name": "Boots", "price": 5, "weight": 3.9 }
Here, we use curly brackets, {}
, to define a dictionary. Then, we define a key and its associated value within the curly brackets. For example, the "name"
key is associated with the "Boots"
value. Each key-value pair must be separated by a comma: