如何计算数组中的结果?
我正在计算数组中模式的出现次数,并希望它以
的形式返回[0, 0, 0]
例如,数组中的每个元素代表搜索结果。
这是我到目前为止所做的......但它似乎只返回[object object] ...
pages=[
"Lorem Ipsum is simply dummy text of the printing and typesetting industry."
,
"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout",
"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable."
]
pattern = prompt("Enter a search string")
var count = {};
for(i=0; i<pages.length; i++)
{
for(j=0; j<pattern.length; j++)
{
if((pages[i].toLowerCase()
.indexOf(pattern.toLowerCase()
.charAt([j])))<0)
{
count[i]++;
}
}
}
alert(count);
答案 0 :(得分:1)
我认为您需要将警报(计数)向上移动2行,如下所示:
var count = {};
for(i=0;i<pages.length;i++)
{
for(j=0;j<pattern.length;j++)
{
if((pages[i].toLowerCase().indexOf(pattern.toLowerCase().charAt([j])))<0)
{
count[i]++;
}
}
alert(count[i]); // but note that it will appear multiple times
}
答案 1 :(得分:1)
var count, allCounts = [];
for(i=0; i<pages.length; i++)
{
count = 0;
for(j=0; j<pattern.length; j++)
{
if((pages[i].toLowerCase()
.indexOf(pattern.toLowerCase()
.charAt([j])))<0)
{
count++;
}
}
allCounts.push(count);
}
alert('[' + allCounts.join(', ') + ']');
我建议您。在任何循环开始之前,先将你的模式设置为一次,这样可以避免在每次循环时执行toLowerCase操作。