這篇的重點主要介紹 TypeScript 中好用的資料結構:Map 及 Set。

首先,要修改 tsconfig.json,新增 lib 欄位:

{
  "compileOnSave": true,
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "outDir": "wwwroot/JS",
    "lib": ["DOM", "ES2015"]
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

接下來測試支援泛形的 Map:

let mapTest = new Map<string, number>([
    ["aaa3", 123],
    ["aaa4", 456]
]);
let v: number = mapTest["aaa3"];

把它當作 C# 的 Dictionary 就可以了。接下來是 Set,跟數學定義中的集合一模一樣,程式碼如下:

let testSet = new Set<number>([1, 2, 2, 2, 2, 4, 7, 3]);
testSet.add(7);
testSet.forEach((i) => {
    console.log(i);
})

雖然指定的 array 中有重覆的元素,但實際上在 Set 是不會有重覆的,後面把數字 7 加進也不會有效果,因為 7 原本就已存在。

參考資料