gpt4 book ai didi

javascript - setTimeout 似乎正在改变我的变量!为什么?

转载 作者:太空狗 更新时间:2023-10-29 14:02:13 28 4
gpt4 key购买 nike

我会很快直接跳到案例中。代码已注释,因此您知道我的意图。基本上,我正在构建一个基于 HTML5 的小型游戏,而不是将内容保存在服务器或 cookie 中,我只会为玩家提供关卡代码。当玩家将代码(以简单哈希的形式)输入文本输入字段并单击按钮加载该级别时,将调用函数“l”。该函数首先检索玩家的条目,然后遍历哈希列表并比较它们。当一场比赛很受欢迎时,应该加载某个级别,但出现错误。我做了一些调试,发现迭代器(“i”)的值在 setTimeout 内发生了变化!我想暂停 1 秒,因为立即加载关卡太快而且看起来很糟糕。

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!
}
}

最佳答案

其他人已经写下了您出现这种行为的原因。现在解决方案:将 setTimeout 行更改为:

(function(i) {
setTimeout(function(){console.log(i)}, 1000);
})(i);

这是有效的,因为它将变量 i 的当前值捕获到另一个闭包中,并且该闭包中的变量不会改变。

关于javascript - setTimeout 似乎正在改变我的变量!为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9540248/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com