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

原文地址:https://www.cnblogs.com/waitinglulu/p/11572850.html