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

如何在JavaScript的Map中为同一键添加多个值而非覆盖原有值

Fixing Map Overwrite Issue: Store Multiple Values per Key in JavaScript

Hey there! I see exactly what's going on here. Your current code uses myMap.set(letter, wordsArray[i]), which replaces the existing value for a key every time you call it—so when you process "hello" first (starting with 'h'), then later "hobby" (also 'h'), the second one overwrites the first.

To fix this, we need each key in the Map to hold an array of words instead of a single word. Here's how to adjust your code step by step:

Key Changes to Implement:

  • Before setting a value, check if the key already exists in the Map
  • If it doesn't exist, initialize it with an empty array and add the current word
  • If it does exist, push the current word into the existing array

Modified Code

const Storage = function(userInput) {
  const wordsArray = userInput.split(' ');
  const myMap = new Map();

  for (let i = 0; i < wordsArray.length; i++) {
    let word = wordsArray[i];
    
    // Remove trailing punctuation marks
    if (word.endsWith(',') || word.endsWith('.') || word.endsWith('!') || word.endsWith(':')) {
      word = word.slice(0, word.length - 1);
    }
    
    // Convert word to lowercase for consistent key matching
    word = word.toLowerCase();
    
    // Get the starting letter as the map key
    const letter = word.slice(0, 1);
    
    // Handle adding the word to the map
    if (myMap.has(letter)) {
      // Key exists: push the word to the existing array
      myMap.get(letter).push(word);
    } else {
      // Key doesn't exist: create a new array with the current word
      myMap.set(letter, [word]);
    }
  }

  console.log(myMap);
}

Storage("Hello, my name is Gleb. My hobby is to learn Javascript");

What This Does

When you run this code, your Map will now store arrays of words for each starting letter:

  • The key 'h' will hold ['hello', 'hobby']
  • The key 'm' will hold ['my', 'my', 'name']
  • All other keys will similarly collect every word that starts with their letter, no more overwrites!

I also cleaned up the code a bit by moving variables inside the function (to avoid global scope pollution) and using a single word variable for better readability.

内容的提问来源于stack exchange,提问作者Gleb Vasiljev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 19:32:42