2013-04-11 140 views
0

我正在學習如何爲Web開發做代碼,並且遇到了問題。兩個代碼幾乎相同的線給我不同的結果:兩條几乎完全相同的代碼行結果不同?

它的重要性
for(i=0; i<=lunarSpells.length; i++){ 
    document.getElementById(lunarSpells[i]).innerHTML = 
    Math.ceil(xpLeft/document.getElementById(lunarSpells[i]+"XP").innerHTML); 
} 
for(i=0; i<=standardSpells.length; i++){ 
    document.getElementById(standardSpells[i]).innerHTML = 
    Math.ceil(xpLeft/document.getElementById(standardSpells[i]+"XP").innerHTML);  
} 

不確定,但這個想法是把一個元素從數組中,發現它在文件中,然後在表格中填寫相應。以下是數組:

var lunarSpells = ["cureOther", "NPCContact", "curePlant", "monsterExamine", "bakePie", "cureMe", "TGMoonclan", 
          "TPMoonclan", "TGBarbarian", "superglass", "TPKhazard", "TGKhazard", "dream", "stringJewellery", 
          "statRestorePotShare", "statSpy", "TPBarbarian", "TPWaterbirth", "cureGroup", "TGWaterbirth", "humidify", 
          "hunterKit", "fertileSoil", "plankMake", "TPCatherby", "TGFishingGuild", "TGCatherby", 
          "boostPotionShare", "TPIcePlateau", "energyTransfer", "healOther", "TGIcePlateau", "vengeanceOther", 
          "vengeance", "healGroup", "spellbookSwap", "magicImbue", "TPFishingGuild"] 

var standardSpells = ["confuse", "sapphire", "weaken", "bananas", "curse", "lowAlch", "TPVarrock", "emerald", "TPLumbridge", "TPFalador", "TPHouse", 
           "superheat", "TPCamelot", "ruby", "TPArdougne", "highAlch", "earth", "water", "diamond", "TPWatchtower", 
           "peaches", "TPTrollheim", "fire", "TPApe", "vulnerability", "air", "dragonstone", "enfeeble", "TOLumbridge", "stun", 
           "TOFalador", "onyx", "TOCamelot"] 

所以我的問題,就是爲什麼lunarspells不同的工作,而standardspells變量是不是?任何幫助都非常感謝,因爲我對HTML和JS還很陌生。

+6

要顯示的任何錯誤?另外,你想使用'<',而不是'<='我想。其實,這可能是代碼失敗的原因。 – 2013-04-11 19:35:31

+1

什麼是預期的和實際的結果? – 2013-04-11 19:36:32

+0

什麼是/不工作? – Huangism 2013-04-11 19:36:36

回答

0

正如所提到的:如果document.getElementById("id_that_doesnt_exist")計算結果爲null

xpLeft/document.getElementById(lunarSpells[i]+"XP").innerHTML 

會失敗(如null.anything是錯誤

這將會停止在<script>塊中的所有進一步的處理,除非你避免錯誤。或try/catch包裹。

所以你的第二個循環將不會達到/執行。

+0

啊哈!雖然這並沒有直接解決問題,但它確實指向了我的錯誤方向。我不小心把兩個相同的元素放在第一個數組中,扔掉.length部分。將<=更改爲<並刪除多餘的元素可解決問題。謝謝! – shermanzach 2013-04-11 19:49:16

相關問題