定义一个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)
本文介绍了如何在JavaScript中创建并遍历Map对象,包括推荐的forEach方法、使用values迭代器以及通过扩展运算符的方式。同时,文章还提到了在不支持ES6环境下的遍历问题,并展示了将Map的值转换为数组的两种方法:Array.from和扩展运算符。这些技巧对于理解和操作JavaScript中的Map数据结构非常实用。
1231

被折叠的 条评论
为什么被折叠?



