我会很快,并直接跳到案件。代码被评论,所以你知道我的意图。基本上,我正在构建一个基于HTML5的小型游戏,并且反对在服务器或cookie中保存内容,我只是给玩家提供一个关卡代码。当玩家将代码(以简单散列形式)输入到文本输入字段中,并单击按钮加载该级别时,将调用函数“l”。该函数首先检索玩家的条目,然后迭代散列列表并对其进行比较。当一场比赛很喜欢,那个水平应该被加载,但是有错误。我做了一些调试,发现iterator(“i”)的值在setTimeout内部发生了变化!我想暂停1秒,因为立即加载关卡会太快而且看起来很糟糕。setTimeout似乎正在改变我的变量!为什么?
levelCodes = //Just a set of "hashes" that the player can enter to load a certain level. For now, only "code" matters.
[
{"code": "#tc454", "l": 0},
{"code": "#tc723", "l": 1},
]
var l = function() //This function is called when a button is pressed on the page
{
var toLoad = document.getElementById("lc").value; //This can be "#tc723", for example
for (i = 0; i < levelCodes.length; i++) //levelCodes.length == 2, so this should run 2 times, and in the last time i should be 1
if (levelCodes[i].code == toLoad) //If I put "#tc723" this will be true when i == 1, and this happens
{
console.log(i); //This says 1
setTimeout(function(){console.log(i)}, 1000); //This one says 2!
}
}
不错的评论,有所有upvotes。 – ninjagecko 2012-03-02 21:13:21
仅供参考,您的代码不会通过jslint的几个原因,并会在一些浏览器中产生错误 – 2012-03-02 21:32:31
@MarkSchultheiss,请解释一下,我认为jsLint是某种评估者,是对的吗?那么,你能告诉我为什么不计算? – corazza 2012-03-02 21:47:41