Map对象值无法递增问题:字符串数组词频统计异常
Hey there! The problem with your code is that you're treating a Map like a plain JavaScript object, which doesn't work the way you think.
When you use this.mapObject[word]++, you're actually adding a direct property to the Map instance itself—not updating the key-value pair stored inside the Map. That's why your Map's values never increment as expected.
Here's the fixed version of your method:
private rankMostFrequent5Words(): void { this.wordList.forEach((word:string) => { if(this.mapObject.has(word)) { // Use Map's get() to retrieve the current value, then set() to update it this.mapObject.set(word, this.mapObject.get(word)! + 1); } else { this.mapObject.set(word, 1); } }); }
A more concise alternative (no if-else needed):
You can simplify this even further by leveraging the fact that Map.get() returns undefined for missing keys. We can fall back to 0 in that case:
private rankMostFrequent5Words(): void { this.wordList.forEach((word:string) => { this.mapObject.set(word, (this.mapObject.get(word) || 0) + 1); }); }
The ! in the first example is a non-null assertion—since we already checked has(word) before calling get(word), we know it won't return undefined, so this is safe.
内容的提问来源于stack exchange,提问作者Muhammad Ahsan

