JavaScript For循环不执行所有代码

时间:2018-03-03 01:53:18

标签: javascript

我有一个使用非常大的for循环的函数,但是当我在AJAX成功调用中检查j的值时,它是6(console.log(j)= 6 6 6 6 6 6)。如果我在成功函数之前放置console.log(j),它会正确显示0 1 2 3 4 5.任何人都可以给我任何关于为什么会发生这种情况或者我缺少什么的指示?

function loadInfo() {
  var knuckles = "";
  for (var i = 1; i < channels.length; i++) {
    knuckles += "&login=" + channels[i];
  }
  $.ajax({
    url: url1 + channels[0] + knuckles,
    type: "GET",
    headers: {
      "Client-ID": "XXXXX"
    },
    success: function (json) {
      for (var j = 0; j < channels.length; j++) {
        console.log(j); // Here is where j has the right values
        $.ajax({
          url: url2 + json.data[j].login,
          type: "GET",
          headers: {
            "Client-ID": "aa20kjc6z0zwwogqpz3wqn3245qzc9"
          },
          success: function (json2) {
            console.log(j); // Here is where j has the wrong values
            var sonic;
            if (json2.stream != null) {
              sonic =
                json2.stream.game +
                "</div>" +
                '<div class="info">' +
                "Apple" +
                "</div>";
            } else {
              sonic =
                '<span class="offlineText">Offline</span>' +
                "</div>" +
                '<div class="info">' +
                "Not currently streaming" +
                "</div>";
            }
            $("#streamerInfo").append(
              streamerBoxStart +
              '<div class="icon" style="background-image: url(' +
              json.data[j].profile_image_url +
              '); background-size: cover;">' +
              "</div>" +
              '<div class="nameGame">' +
              json.data[j].display_name +
              " ★ " +
              " " +
              sonic
            );
          }
        });
      }
    }
  });
}

它是一个可变范围的东西,循环的东西,我完全缺少的东西? (注意:这只是我的代码的一个功能,其他东西在实际代码的上方/下方定义。)

1 个答案:

答案 0 :(得分:0)

举例说明:JavaScript closure inside loops – simple practical example

包围j值。

function loadInfo() {
  $.ajax({
      success: function (json) {
      for (var j = 0; j < channels.length; j++) {
        console.log(j); // Here is where j has the right values
        (function(j) { // Add this line
            $.ajax({
              success: function (json2) {
                console.log(j); // Here is where j also has the right values
              }
           });
        )(j); // Add this line
    }
  });
}