[英]How to add two values to the same index in map type array
let wordsArray; let indexArray = []; let index; let myMap = new Map(); const Storage = function(userInput){ wordsArray = userInput.split(' '); //remove ',' and '.' for( let i = 0; i < wordsArray.length ; i ++){ if(wordsArray[i].endsWith(',') || wordsArray[i].endsWith('.') || wordsArray[i].endsWith('!') || wordsArray[i].endsWith(':')) { let temp = wordsArray[i]; wordsArray[i] = temp.slice(0, temp.length - 1 ); } //ToLowerCase let temp = wordsArray[i] wordsArray[i] = temp.toLowerCase(); //IndexCreation let letter = wordsArray[i].slice(0,1); indexArray.push(letter); //Add to Array myMap.set(letter,wordsArray[i]); } console.log(myMap); } Storage("Hello, my name is Gleb. My hobby is to learn Javascript");
The elements of your "index" map should be arrays rather than strings. “索引”映射的元素应该是数组而不是字符串。 When adding a word, check if the first letter already exists in the map, and if not, initialize it to an empty array.
添加单词时,检查第一个字母是否已经存在于地图中,如果不存在,则将其初始化为空数组。 Then, add a word to
map[letter]
:然后,在
map[letter]
中添加一个单词:
let index = new Map word = 'hello' letter = word[0] if (!index.has(letter)) index.set(letter, []) index.get(letter).push(word) word = 'hobby' letter = word[0] if (!index.has(letter)) index.set(letter, []) index.get(letter).push(word) console.log([...index])
// Add to Array
if (myMap.has(letter)) {
let temp = myMap.get(letter);
temp = [temp,wordsArray[i]]
myMap.set(letter, temp)
} else {
myMap.set(letter, wordsArray[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.