In my AppsScript project, I had been creating a dictionary using this syntax:
let arr = [];
arr["a"] = 5;
But for some reason, it just stopped working. When I print arr
it is an empty array. See picture:
Using this syntax used to work for me. Does anyone know what might have changed?
I am looking for an alternative way to create a dictionary now. Do you know if there is another way to define a dictionary so I can access the array like arr["a"]
?
1
Arrays are different from plain objects
Array keys should be integers. The log fails to show the key, because you are using non-numeric keys for the array, which doesn’t impact its indexing or length. With this, whenever you are trying to call your array it won’t display anything as the array
is intended to hold indexed elements and usually accessed with numeric indices, as they are ordered collections.
The best fit to create a dictionary is to use Objects
as it is for key-value pairs. You can refer to the code below as suggested by @Tanaike.
function nothingsWrong() {
const obj = {};
obj["a"] = 5;
console.log(obj);
}
Which gives you the result below:
Note however that, under the hood, even arrays are objects. So, the arr
in your original code will still have the a
key. It just isn’t logged or enumerated. But you can still access it:
console.info(arr['a']);//Logs 5
REFERENCES:
- Arrays
- Objects