Javascript for loop scope takes last variable

前端 未结 4 1705
清酒与你
清酒与你 2020-12-22 02:09

This works:

  var toggler = function(most){
    var open = $(\'#toggle_\' + most + \' .minus\').is(\':visible\');

    if(open){
      $(\'#toggle_\' + most          


        
4条回答
  •  旧巷少年郎
    2020-12-22 02:28

    Your loop is constructed incorrectly. When you want to set a variable in a loop to access an element of an array or object, this is the correct syntax:

    var test = [];
    for(var i = 0; i < test.length; test++)
        (function(index){
            // do cool stuff with test[index]
        })(i);
    

    This creates a closure over the variable i. If you aren't familiar with the syntax, here's what happens:

    1) We define a closure (the opening ()'s after the for statement)

    2) We define an anonymous function to take the index parameter

    3) We pass the index into the closure (i.e. we execute the function)with the final set of ()'s.

    These three steps happen for every iteration of the loop. If you don't use the closure to capture the index value, then when the array access is actually made, the index in this example would be +1 too many, and cause errors at runtime.

    Cheers

提交回复
热议问题