You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Map对象值无法递增问题:字符串数组词频统计异常

Fixing Map Value Increment Issue for Word Frequency Count

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:55:37