2013-04-11 110 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

相关问题