因此,我对代码进行了一些编辑,但我一直在尝试计算指定记录中模式出现的次数。
如果搜索类似 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/