定義一個Map: let map = new Map<string, string>(); map.set("a", "1");
遍歷方式:
1.(推薦使用) map.forEach((value, key) => { }) (參數順序:value在前, key在后)
2. let iterator = map.values(); let r: IteratorResult<string>; while (r = iterator.next(), !r.done) { console.log(r.value); }
3. for(let i of map.values()){ console.log(i); } (適用於es6)
若提示錯誤: Type 'IterableIterator<string>' is not an array type. 則是因為target != es6, 不支持遍歷IterableIterator
坑:
for(let i in map.values()){ console.log(i); } (雖不報錯但不會進入循環)
將map的value(key) 轉換成數組:
1. Array.form: let a = Array.from(departmentMap.values());
2. 擴展表達式:let a = [...departmentMap.values()]; (適用於es6)