2013-07-19 20 views
0

我使用下面的代碼來查找那些未列在我的觀察列表(項目數組列表)中的項目。但是,每當我運行此代碼時,瀏覽器會凍結。如果我刪除最後的其他部分,那麼程序運行良好,並打印來自RSS源中的查看列表中的項目。如何篩選rss數據對javascript數組

可以在任何一個告訴我,什麼是錯的我else部分,它不打印觀察名單中沒有找到的物品?我的目標是能夠打印從RSS提要的項目,在未找到我的手錶清單數組。我的手錶清單數組中有大約700件物品,rss大約有1000件物品!

<script> 
$.getJSON('http://anyorigin.com/get?url=http://www.somesite.com/rss.php&callback=?', function(data){ 

var p=0; 

var siteContents = data.contents; 
var parser=new DOMParser(); 
xmlDoc=parser.parseFromString(siteContents,"text/xml"); 

var items = xmlDoc.getElementsByTagName("item"); 


for(i = 0; i < items.length; i++) 
{ 

document.myform2.outputtext2.value +=items[i].getElementsByTagName("itemname")[0].childNodes[0].nodeValue+"\n"; 


var myVariable =items[i].getElementsByTagName("itemname")[0].childNodes[0].nodeValue; 



items=["mango","apple","orange","banana","book","pen"]; 



       for (var m=0;m<items.length;m++) 
       { 

        if (myVariable == items[m]) 
        //if (items[m] == myVariable) 
        { 
         //do nothing 

         p++; 
         document.myform3.outputtext3.value +=myVariable+"\n"; 
        } 
        else 
        { 
         //alert (myVariable); 
        document.myform4.outputtext4.value +=myVariable+"\n"; 

        }; 
      }; 



};//end of outer for 

}); 


</script> 
+0

纔有可能爲您作出一個http://jsfiddle.net/麻煩用拍? – Banning

+0

爲什麼您將該數組分配給您分配了xml節點集合的相同'items'變量? – Bergi

回答

1

你的邏輯被顛倒過來。您當前的腳本(使用else聲明)每次打印一個項目時不會與監視列表中的任何一個相同 - 每個項目的打印次數與觀察列表的長度一樣多;這在該輸出中產生了700000行!

您必須將該條件移到循環之外。僞代碼:

found = false 
foreach item in watchlist 
    if item == myvariable // the one you're searching for 
     found = true 
     break 

if found 
then putItSomewhere() 
else putItSomewhereElse() 

在實際的腳本,你不會使用一個循環,但只是indexOf Array method

if (items.indexOf(myVariable) == -1) { 
    // not found, so output it 
    document.myform4.outputtext4.value +=myVariable+"\n"; 
} 
+0

bergi很多很多謝謝,解決了凍結問題。我從來不知道我可以使用indexof來搜索數組中的項目! – user1788736