数组返回indexOf而不是pattern的计数

时间:2011-11-05 14:07:57

标签: javascript

所以我编写了一些我的代码,并且我一直试图计算指定记录中模式出现的次数。

我希望数组以 2,1,0 的形式返回,如果搜索 中的内容,但目前我得到的只是 13,19, - 1

我真的很感激有关如何改进我的代码的任何提示。

books = [
    {
    title: "Inheritance: Inheritance Cycle, Book 4",
    author: "Christopher Paolini",
    },
{
    title: "The Sense of an Ending",
    author: "Julian Barnes"},
{
    title: "Snuff Discworld Novel 39",
    author: "Sir Terry Pratchett",
    }
]
search = prompt("Title?");

function count(books, pattern) {

        var num = 0;
        var result = [];
        for (i = 0; i < books.length; i++) {
            var index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase());
            do {
                result[i] = index;
                index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase(), index + 1);
            }
            while (index >= 0)
            num = 0;
        }
        return result;
    }
alert(count(books, search));

4 个答案:

答案 0 :(得分:4)

您需要保留计数,而不是结果中找到它的索引。只有当索引大于或等于零时,才应增加计数。注意我也进行了一些优化,以减少转换字符串所需的次数。我还添加了一个使用正则表达式的不同版本。

function count(books, pattern) {
    var result = [];
    for (i = 0; i < books.length; i++) {
        var index = -1, // set to -1 so that the first iteration will set it to 0
            title = books[i].title.toLowerCase(),
            realPattern = pattern.toLowerCase();
        result[i] = 0;
        do {
            index = title.indexOf(pattern, index + 1);
            if (index >= 0) {
               result[i] = result[i] + 1;
            }
        }
        while (index >= 0)
    }
    return result;
}

更好的替代方案

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

function count(books, pattern) {
    var result = [];
    for (i = 0; i < books.length; i++) {
        var regex = new RegExp(RegExp.escape(pattern),'gi'),
            matches = books[i].title.match(regex);
        result[i] = matches ? matches.length : 0;
    }
    return result;
}

答案 1 :(得分:1)

您可以使用for循环并将循环var推送到结果变量中。

jsfiddle

var arr = ['a', 'b', 'c', 'a'];

function count(books, pattern) {   
    var results = [];
    for (var index in arr) {
        if (arr[index] === pattern) {
          results.push(index);
        } 
    }
    return results;
}

console.log(count(arr, 'a'));

答案 2 :(得分:1)

试试这很简单

function count(books, pattern) 
{

var num = 0;
var result = Array();
for (i = 0; i < books.length; i++) 
{
    var times = books[i].title.toLowerCase().split(pattern.toLowerCase());
    if(times.length - 1 >= 0)result[i] = times.length - 1;
}
return result;
}

希望你会发现这很有用!

答案 3 :(得分:1)

您可以使用match大量简化代码。我在这里做了一个jsfiddle:http://jsfiddle.net/NTWNn/它看起来像这样:

var books = [
    {
        title: "Inheritance: Inheritance Cycle, Book 4",
        author: "Christopher Paolini",
    },
    {
        title: "The Sense of an Ending",
        author: "Julian Barnes"
    },
    {
        title: "Snuff Discworld Novel 39",
        author: "Sir Terry Pratchett",
    }
]
search = prompt("Title?");

function count(pattern)
{
    var results = [];
    var matches = null;
    pattern = new RegExp(pattern, "g")

    for (i = 0; i < books.length; i++) {
        results[i] = 0;
        matches = books[i].title.toLowerCase().match(pattern);
        if(matches != null) {
            results[i] = matches.length;
        }
    }
    return results
}

alert(count(search))