javascript - 在数组 Javascript 中搜索字符串

标签 javascript

我需要用 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/

相关文章:

javascript - 在 Controller 中调用它时出现 ng-modal 问题

javascript - AngularJS 的 ng-options

javascript - 如何重置 Chart.Js 的图表?

javascript - 如何禁用 div 中的 root ng-click 按钮?

java - jboss 上的 Yui 压缩器 StringIndexOutOfBoundsException

javascript - 选择小费时如何更新总金额

javascript - meteor 动态分类列表

javascript - 允许用户通过网络摄像头直播

JavaScript:使用reduce函数的句子变体

javascript - 使用 Typescript 时,如何从代码中执行 return defer.resolve() ?