javascript - 数组返回indexOf而不是模式计数

标签 javascript

因此,我对代码进行了一些编辑,但我一直在尝试计算指定记录中模式出现的次数。

如果搜索类似 in 的内容,我希望数组返回为 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));

最佳答案

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

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;
}

关于javascript - 数组返回indexOf而不是模式计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8020663/

相关文章:

javascript - 在 D3 中缩小时如何按时间尺度对图标进行聚类?

javascript - 代码可以在本地运行,但不能在 AWS lambda 上运行

javascript - Jquery 调整大小事件在 Phonegap IOS 中不起作用?

javascript - 如何异步运行 Docker 命令?

javascript - 如何为注册表创建圆形轮廓仪

javascript - iFrame Resizer 将 iFrame 的高度增加到无穷大

javascript - 如何在一行中强制显示div内的所有固定宽度元素

Javascript 从服务器下载 zip 文件

javascript - Neo4j中有没有办法根据 "dateProperty"查询节点

javascript - cytoscape 中的边缘可以有多种颜色吗