I tried the following, but the dictionary only had one key.
class dog
{
}
dic = {}
for(let i=0; i<3; i++)
{
dic[new dog()] = i;
}
for(var item in dic)
{
console.log(dic[item]);
}
But that was not what I intended. I wanted it to work like the following C# code, whose output is 0 1 2. It seems that each new dog() in the JS code above is treated as the same object and thus the value overwrites the previous one. How can I modify the JS code so that it work like the C# code below?
using System;
using System.Collections.Generic;
class dog
{
}
public class Program
{
public static void Main()
{
var dic = new Dictionary<object,int>();
for(var i=0; i<3; i++)
{
dic[new dog()] = i;
}
foreach(var item in dic.Keys)
{
Console.WriteLine(dic[item]);
}
}
}
>Solution :
Object keys can only be one of two type i.e. Strings or Symbols. To achieve the desired behaviour, you can use a Map instead of an object as a dictionary.
class Dog {
}
const map = new Map();
for (let i = 0; i < 3; i++) {
map.set(new Dog(), i);
}
for (const [key, value] of map.entries()) {
console.log(value);
}