Javascript for循环传递计数变量

时间:2014-03-19 17:53:17

标签: javascript jquery for-loop

   for (var i=0 ; i<10 ; i++){

      var myFunction = function(something){
         console.log(i);
      }

      $.ajax({

        url: "something.json",
        dataType: "json",
        success: function( response ) {

               myFunction(response.something);

        }
      });               

    }

每次循环for循环时,如何访问myFunction中的最新i。似乎myFunction中的最新i无法访问,因此它不会从i = 0到9进行记录。

3 个答案:

答案 0 :(得分:1)

这可能不是最有效的解决方案。但它确实有效。您可以将对象变量设置为请求,并使用myFunction上的.call

来访问它们
for (var i=0 ; i<10 ; i++){

  var myFunction = function(something){
     console.log(this.localData.i);
  }

  $.ajax({
      url: "/echo/json/",
      dataType: "json",
      //Set the i variable to this request
      localData: {
          i: i
      },
      success: function( response ) {
        //call myFunction with this as the context, and you'll be able to access localData by using this.localData.i
        myFunction.call(this, response.something)
      }
  });               

}

这是一个小提琴:http://jsfiddle.net/XxRAv/1/

答案 1 :(得分:0)

      function myFunction(i,something){
         console.log(i);
         console.log(something);
      }

    for (var i=0 ; i<10 ; i++){
      $.ajax({

        url: "something.json",
        dataType: "json",
        success: function( response ) {

               myFunction(response.something);

        }
      });               

    }

答案 2 :(得分:0)

您正在查看late binding的效果。一种解决方案是创建一个包装函数并调用它,它将返回正确的函数:

  var myFunction = function(i){ 
     return function(something){ console.log(i); };
  }(i);
相关问题