When iterating a map in Typescript, the forEach
method behaves strangely where the key and value must be inverted.
However, using a regular for
loop works correctly as expected.
const map = new Map<number, number>()
const uniq = new Set<number>();
// This won't return anything if a condition is true
map.forEach( (v,k) => { // Also note that k and v are inverted
if(uniq.has(v)) return false
uniq.add(v)
});
// This will work without any issues
for (const [_, v] of map.entries()) {
if(uniq.has(v)) return false
uniq.add(v)
}
The question remains: Why does the forEach
method not break or return?