循环范围的Javascript采用最后一个变量 [英] Javascript for loop scope takes last variable

查看:85
本文介绍了循环范围的Javascript采用最后一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样可行:

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

    if(open){
      $('#toggle_' + most + ' .minus').hide();
      $('#toggle_' + most + ' .plus').show();
    }else{
      $('#toggle_' + most + ' .plus').hide();
      $('#toggle_' + most + ' .minus').show();
    }

    $('#' + most + ' ol.tlist').toggle(open);
  };

  $('#toggle_mostviewed').click(function(){ toggler('mostviewed'); });
  $('#toggle_mostshared').click(function(){ toggler('mostshared'); });
  $('#toggle_mostrecent').click(function(){ toggler('mostrecent'); });

但这不是:

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

    if(open){
      $('#toggle_' + most + ' .minus').hide();
      $('#toggle_' + most + ' .plus').show();
    }else{
      $('#toggle_' + most + ' .plus').hide();
      $('#toggle_' + most + ' .minus').show();
    }

    $('#' + most + ' ol.tlist').toggle(open);
  };

  var t = ['mostviewed','mostshared','mostrecent'];
  for(var i = 0 ; i  < t.length; i++ ){
    var j = t[i];
    $('#toggle_' + j).click(function(){ toggler(j) });
  }

就像for循环被替换一样:

Is like the for loop was "replaced" by:

  $('#toggle_mostrecent').click(function(){ toggler('mostrecent'); });

即。最后一次迭代是唯一重要的。

i.e. the last iteration is the only that counts.

推荐答案

你的循环构造不正确。如果要在循环中设置变量以访问数组或对象的元素,这是正确的语法:

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);

这会在变量i上创建一个闭包。如果您不熟悉语法,请执行以下操作:

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

1)我们定义一个闭包(在for语句之后的开头())

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

2)我们定义一个匿名函数来获取索引参数

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

3)我们将索引传递给闭包(即我们用最后一组()来执行函数。

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

这三个步骤发生在循环的每次迭代中。如果不使用闭包来捕获索引值,那么当实际进行数组访问时,此示例中的索引将太多+1,并在运行时导致错误。

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.

干杯

这篇关于循环范围的Javascript采用最后一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆