我现在正在学习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"one_answers"是"单词时,我经常返回"未定义",因为这些单词对这些单词进行计数。例如," be be be be be be be返回"未定义",因为"one_answers"是。有人可以帮助阐明这里发生了什么吗?谢谢。
您的代码不可读:
- 代码的块太长
- 非信息变量名称(例如
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;
索引i
是strArray
中当前单词的索引。您可以通过删除此行进行修复,然后做
resultCount.push(counter)
以for (var j = i + 1; j < strArray.length; j++)
开头的循环结束后。