typescript遍歷Map


定義一個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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM