传递数组时,全局变量将被吊起

时间:2019-08-28 14:00:08

标签: javascript hoisting

很抱歉,如果他们的某个地方有类似的答案。所有悬而未决的答案似乎都无法完全回答我的问题。我有一个全局变量,似乎只能“挂起”(我不太了解) 当我将数组传递给函数时。我不明白为什么这会改变什么。

var i = 0 //counter for show pattern


//this first function works fine. the console.log shows i = 0
 function myLoop () {           
    console.log("My loop:" + i);
    setTimeout(function () {    
       alert('hello');          
       i++;                     
       if (i < 3) {            
          myLoop();             
       }                        
    }, 3000)
 }

//this second function shows i as undefined. If I remove list, then the console logs i as 0 which is correct

function showPattern(list){
    console.log(list[0] + i);
    setTimeout(function(){      
        console.log("IT works!");
        //for each square on the screen
        $(".square").each(function(j,obj){
            console.log($(obj).attr("id") + "/" + list[i]);
            //if the ID is equal to the pattern number
            if(parseInt($(obj).attr("id")) === parseInt(list[i])){

                $(obj).css("opacity","1");
                setTimeout(function(){
                    $(obj).css("opacity",".5");
                }, 500);
            }
        })
        i++;
        if( i < list.length){
            showPattern();
        }

    },3000);
}

2 个答案:

答案 0 :(得分:0)

我不认为“ var i”的起吊根本不是您的问题。第二个功能将中断(当您不传递数组时),因为您尝试在控制台日志中引用list [0]。您正在尝试访问不存在的数组的索引0。如果没有传递数组,则将引发错误。

这部分代码也将存在该问题:

if( i < list.length){
    showPattern();
}

答案 1 :(得分:-1)

通过提升,仅提升了语句var i = 0var i)的声明部分。 i = 0部分没有。因此,当您的代码(没有list)运行并遇到:

list[i]

i未定义。但是,当您通过list然后上一行时:

list[0] + i

+符号将i隐式转换为与list[0](字符串或数字)兼容的默认类型。