gpt4 book ai didi

javascript - 如何计算每个单词在字符串中出现的次数?

转载 作者:行者123 更新时间:2023-12-03 04:49:45 25 4
gpt4 key购买 nike

我现在正在学习 JavaScript,正在开发一个函数,该函数将计算单词在字符串中出现的次数,然后将答案作为对象吐出。根据本网站上类似线程的一些建议,我决定使用 .split 和计数器函数来创建二维数组,然后用结果填充对象。当我在使用某些字符串时遇到一些问题时,我正在使用示例文本运行测试。我不明白为什么有些计数器显示为未定义。

function countWords(str) {
var answer = {};
if (str === '') {
return answer;
}
var strArray = [];
strArray = str.split(' ');
//strArray is an array that holds the words as separate strings
console.log('strArray: ' + strArray);
var resultWords = [];
var resultCount = [];
var counter = 0;

// only if the word doesnt show up in resultWords, push it in, and increase the counter. if it has shown up, disregard
for (var i = 0; i<strArray.length; i++) {
counter = 0;
if (resultWords.indexOf( strArray[i] ) === -1) {
resultWords.push(strArray[i]);
counter += 1;
// if the word shows up again, increase the counter
for (var j = i + 1; j < strArray.length; j++) {
if (resultWords[i] === strArray[j]) {
counter += 1;
}
// push to resultCount the counter for each word
resultCount[i] = counter;
}
}
// create an object where the key is the word from resultWords and the value is the number from wordCount
for (var k = 0; k < resultWords.length; k++) {
answer[ resultWords[k] ] = resultCount[k];
}
}
console.log('resultWords: ' + resultWords);
console.log('resultCount: ' + resultCount);
return answer;
}

var sample = 'how now brown cow how now';
console.log(sample);
var output = countWords( sample );

我发现当我在示例中使用“this”和“is”这两个词时,我经常返回“undefined”作为这些词的字数。例如,“to be or not to be”对于“that”和“is”返回“未定义”。有人可以帮助解释一下这里发生了什么吗?谢谢。

最佳答案

您的代码不可读:

  • 代码块太长
  • 非信息性变量名称(例如 answer )

接下来,你的算法非常慢:你可以通过只解析整个数组一次来计算单词数。

最后但并非最不重要的一点是,您应该创建 answer循环外的数组。

这是一个使用现代 JavaScript 功能的较短实现(为了学习):

function countWords(str) {
const wordCounts = new Map()
str.split(' ').forEach(word => {
const currentWordCount = wordCounts.get(word) || 0
wordCounts.set(word, currentWordCount+1)
})

/* Reproduce your output */
const resultWords = [...wordCounts.keys()]
const resultCount = [...wordCounts.values()]
console.log('resultWords: ' + resultWords);
console.log('resultCount: ' + resultCount);

return wordCounts
}

在较旧的js环境中,您无法使用Map和箭头函数:

function countWords(str) {
const wordCounts = {}
str.split(' ').forEach(function(word) {
const currentWordCount = wordCounts[word] || 0
wordCounts[word] = currentWordCount+1
})

/* Reproduce your output */
const resultWords = Object.keys(wordCounts)
const resultCount = resultWords.map(function(word) { return wordCounts[word] })
console.log('resultWords: ' + resultWords);
console.log('resultCount: ' + resultCount);

return wordCounts
}

回到你的代码,你会得到一些undefined因为这一行:

// push to resultCount the counter for each word
resultCount[i] = counter;

索引istrArray 中当前单词的索引。您可以通过删除此行来修复它,然后执行

resultCount.push(counter)

for (var j = i + 1; j < strArray.length; j++) 开头的循环结束后.

关于javascript - 如何计算每个单词在字符串中出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42709901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com