我需要用 javascript 编写一个函数,它在文本中找到一个字符串并打印该字符串在文本中找到的次数。这是我的代码,由于某种原因无法正常工作....请帮助
var word = 'text',
text = 'This is some wierd stupid text to show you the stupid text without meaning text just wierd text oh text stupid text without meaning.';
searchWord(word, text);
function searchWord(word, text) {
switch (arguments.length) {
case 1: console.log('Invalid input, please try again'); break;
case 2: var array = text.split(' ');
for (var i = 0; i < array.length; i++) {
var count = 0;
if (array[i] === word) {
count ++;
}
}
console.log('Word ' + word + ' is repeated in the text ' + count + ' times');
}
}
最佳答案
您的代码中存在一个小问题。你必须移动
var count = 0;
在 for 循环之外。
关于javascript - 在数组 Javascript 中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30681571/