Skip to main content

Records

Records (also called dictionaries) are dynamic objects, objects than can be changed during runtime.

Record declaration

You can declare a dictionary using the keyword Record followed by the key and value types between <>:

// Defining a dictionary with the keys being strings and the values lists of numbers. 
var rec: Record<string, number[]> = {}

Record initialization

Records can be inizialized writing key-value pairs.

var rec: Record<string, number[]> = {
"a": [1, 2, 3],
"b": [4]
};

Accessing and modifying record values

You can access and modify record values using the key. Adding new key-value pairs can be done by simply accessing an inexistent key.

// Accesing elements
var a = rec["a"]; // a = [1, 2, 3];
var a0 = rec["a"][0]; // a0 = 1
var b = rec["b"]; // b = [4]

// Adding elements
rec["c"] = [5, 6];

Iterating over records

You can iterate over the keys of a record using Object.keys() or Object.values().

var userScores: Record<string, number> = {
"player1": 100,
"player2": 150,
"player3": 200
};

// Using Object.keys()
var keys = Object.keys(userScores);
var sumScores = 0;
for(var i = 0; i < keys.length; i++){
sumScores = userScores[keys[i]];
}

// Using Object.values()
var values = Object.values(userScores);
var sumScores = 0;
for(var i = 0; i < values.length; i++){
sumScores = values[i];
}