如何在JavaScript的Map中为同一键添加多个值而非覆盖原有值
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

