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

前端之家收集整理的这篇文章主要介绍了javascript – setTimeout似乎正在改变我的变量!为什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我会很快,直接跳到案件中.代码评论,所以你知道我的意图.基本上,我正在构建一个基于 HTML5的小型游戏,并且反对在服务器或cookie中保存内容,我只会向玩家提供一个级别代码.当玩家将代码(以简单散列的形式)输入文本输入字段,并单击按钮以加载该级别时,将调用函数“l”.该函数首先检索玩家的条目,然后遍历散列列表并进行比较.当匹配喜欢时,应该加载某个级别,但是存在错误.我做了一些调试,我发现迭代器(“i”)的值在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!
        }
}

解决方法

for循环连续递增i直到满足循环条件,即使for循环中的代码没有执行,当setTimeout中的代码执行时,它显示i的当前值 – 即2.
原文链接:https://www.f2er.com/js/159093.html

猜你在找的JavaScript相关文章