它目前找到第一个重复最多的词,现在我需要它来抓取多个词,如果有更多的词被使用。我的代码失败的部分是当我 split() 分隔单词然后 Set() 删除重复项时。我认为我的问题来自从字符串切换到数组?我只需要一个简单的方法来让它工作,任何建议都值得赞赏。谢谢!
let str = "She she sells sea shells down by the sea shore boop seasalt"
function commonWord(){
if (str.length === 0) {
return null
}
str = str.toLowerCase()
let maxCount = 0
let maxWord = ""
str = str.split(" ")
str.forEach(word=>{
let wordValue = str.filter(w => w === word).length
if(wordValue > maxCount){
maxCount = wordValue
maxWord = word
}
else if(wordValue == maxCount){
maxWord = maxWord + " " + word
maxWord = maxWord.split(" ")
maxWord = [...new Set(maxWord)]
}
})
console.log(maxWord)
}
commonWord()
答案 0 :(得分:1)
在我看来,最简单的方法就是使用数组开头:
let str = "She she sells sea shells down by the sea shore boop seasalt"
function commonWord(){
if (str.length === 0) {
return null
}
str = str.toLowerCase()
let maxCount = 0
let maxWord = []
str = str.split(" ")
str.forEach(word=>{
let wordValue = str.filter(w => w === word).length
if(wordValue > maxCount){
maxCount = wordValue
maxWord.length = 0
maxWord.push(word)
}
else if(wordValue == maxCount){
maxWord.push(word)
}
})
console.log(maxWord)
}
commonWord()
如果有任何问题,我很抱歉,我对 js 还很陌生。
答案 1 :(得分:1)
一旦您不仅要查看最大值,还要查看“最大值”列表,那么在构建列表时存储迄今为止最常用的单词将很有帮助:
let str = "She she sells sea shells down by the sea shore boop seasalt"
let max = 0;
const ob = str.toLowerCase().split(' ').reduce((obj,cur) => {
if (obj[cur]){
obj[cur]++;
} else {
obj[cur] = 1;
}
if (max < obj[cur]) max = obj[cur];
return obj}
,{})
console.log(ob)
const final = Object.entries(ob).filter(([k,v]) => v === max).flatMap(([k,v]) => k)
console.log(final)
@Mulan 建议使用 Map 之后:
let str = "She she sells sea shells down by the sea shore boop seasalt"
let max = 0;
const mymap = str.toLowerCase().split(' ').reduce((obj,cur) => {
let currentVal = obj.get(cur);
if (currentVal){
obj.set(cur,++currentVal);
} else {
obj.set(cur,1);
}
if (max < currentVal) max = currentVal;
return obj}
,new Map())
for (let [key, value] of mymap) {
console.log(key + ' = ' + value)
}
const final = Array.from(mymap).filter(([k,v]) => v === max).flatMap(([k,v]) => k)
console.log(final)