2011-11-02 81 views
0

如何计算数组中的结果?在JavaScript数组中计算结果

我计数模式的出现在阵列中并且可能喜欢它作为

[0, 0, 0] 

返回例如与表示搜索结果中的数组的每个元素。

这是我到目前为止已经完成了...但它似乎只返回[对象对象] ...

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

嗯,那是因为它是一个对象。将它指向控制台以查看其内容:'console.dir(count);' –

+0

我已更新问题:-) – methuselah

+0

为什么要迭代每个字符或搜索字符串?你不想只搜索整个模式吗? –

回答

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你的模式一次,这将避免做与toLowerCase操作I *进行j次。

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 
      } 
+0

循环内的警报 - 听起来很有趣。控制台请。 –

+0

嘿@Amr ElGarhy我已经更新了代码 – methuselah