提取模式计数并将其转储到数组中

时间:2011-11-05 03:30:03

标签: javascript

我的程序当前循环遍历数组,并计算模式在所有数组中出现的次数。

例如:如果我在提示时搜索“ at ”,我将最终:

0,1,2,3,4

但我真的想以

结束
4,1

在阵列1中出现4次,在阵列2中出现一次。

这是模式在阵列中出现的次数。

关于如何实现这一目标的任何建议?

非常感谢提前!

web = ["cat fat hat mat", "that the who"];

var search = prompt('Search?');

function count(web, pattern)
{
    if (pattern)
    {
        var num = 0;
        var result = [];
        for (i = 0; i < web.length; i++)
        {
            var current = web[i];
            var index = current.indexOf(pattern);
            while (index >= 0)
            {
                result[result.length] = num++;
                index = current.indexOf(pattern, index + 1);
            }
        }
        return result;
    }
    else
    {
        return ("Nothing entered!");
    }
}
alert(count(web, search));

3 个答案:

答案 0 :(得分:0)

var web = ["cat fat hat mat", "that the who"];

var search = prompt('Search?');

function count(web, pattern)
{
    if (pattern)
    {
        var num = 0;
        var result = [];
        for (i = 0; i < web.length; i++)
        {
            var current = web[i];
            var index = 0;
            do{
                result[i] = num++;
                index = current.indexOf(pattern, index + 1);

            }while (index >= 0)
            num = 0;
        }
        return result;
    }
    else
    {
        return ("Nothing entered!");
    }
}
alert(count(web, search));

这也有效

var web = ["cat fat hat mat", "th the who"];

var answer = prompt('Search?');
var search = new RegExp( answer, "g");

function count(web, pattern)
{
    var result = [];
    for(var i=0; i< web.length; i++){
        var matches = web[i].match(search) || [];
        result[i] = matches.length;
    }

    return result.join(",");
}
alert(count(web, search));

答案 1 :(得分:0)

var s = prompt('Search?');
var web = ["cat fat hat mat", "that the who"];
function count(search,arr){
 var reg = new RegExp(search,'g');
 var matches = [];
 for(var i=0; i<arr.length; i++){
  matches.push(arr[i].match(reg) ? arr[i].match(reg).length : 0);
 }
return matches; 
}

然后,就这样称呼它:

count(s,web);

它将返回[4,1]

这会将任何数组作为第二个参数。

Demo

答案 2 :(得分:0)

  • 使用.match代替.indexOf,然后您将获得该号码 直接匹配
  • 别忘了申报i var
  • 将验证放在顶部,更容易理解

重写:

var web = ["cat fat hat mat", "that the who"]
  , search = prompt('Search?')

function count(web, pattern){
    if (!pattern){
        return "Nothing entered!"
    }

    var result = []
      , exp = new RegExp(pattern, "g")

    for(var i = 0; i < web.length; i++){
        var matches = web[i].match(exp)
        result.push(matches ? matches.length : 0)
    }
    return result
}

alert(count(web, search))

最重要的:避免在阻止{之前的换行符。

此:

return
{
   x: 1
}

相当于

return;
{
   x: 1
};

return undefined