我正在尝试遍历数组以检查特定模式,但此后一直没有任何输出。不知道我做错了什么!我将不胜感激任何帮助!
我正在测试或帽子上的图案。
sample = ["cat fat hat mat", "that the who"]
searchTerm = prompt("Testing?");
function count(sample, searchTerm)
{
for (i=0;i<sample.length;i++)
{
if (sample[i].indexOf(searchTerm) == -1)
{
return 0;
}
return count(sample.substring(sample.indexOf(searchTerm) + searchTerm.length), searchTerm) + 1;
}
}
alert(count(sample, searchTerm));
重新编码
search = ["cat fat hat mat", "that the who"];
var pattern = prompt('Search?');
function count(sample, searchTerm)
{
var count, i;
count = 0;
for (i=0; i < sample.length; i++)
{
if (sample[i].indexOf(searchTerm) !== -1)
{
count++;
}
}
return count;
}
count(search, pattern);
我已经重做了一切,但仍然没有任何输出。
最佳答案
这段代码有两个问题。最直接的一个是您在substring
而不是array
上调用string
。
return count(sample.substring ...
你可能想说
return count(sample[i].substring ...
但是,第二个问题是您需要对逻辑进行一点划分。您需要将其分为几个部分,这些部分计算单词中出现的次数以及遍历数组的次数。今天,它们交织在一起,并导致奇怪的行为,因为您最终将非数组传递给期望数组的地方
function count(sample, searchTerm) {
var num = 0;
for (i=0;i<sample.length;i++) {
var current = sample[i];
var index = current.indexOf(searchTerm);
while (index >= 0) {
num++;
index = current.indexOf(searchTerm, index + 1);
}
}
return num;
}
工作提琴:http://jsfiddle.net/wrNbL/
关于javascript - 遍历数组以检查模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8012174/