【问题标题】:For loop proceeding out of orderFor循环乱序进行
【发布时间】:2015-12-09 17:12:08
【问题描述】:

新手,请告诉我是否遗漏了信息或类似的内容。

我正在处理的代码可以在这里看到:http://codepen.io/hutchisonk/pen/mVyBde,我还在下面粘贴了 javascript 的相关部分。

我无法理解为什么这段代码会这样。快速概述 - 我在顶部定义了一些变量,创建了一个函数来获取我需要的数据并将其构建成一个非常小的列表。这似乎按计划进行。

概述函数后,我然后遍历“朋友”数组中的每个“朋友”,每次调用该函数一次。我已经在输出上给朋友编号,以帮助澄清发生了什么。我已经尝试了很多方法,包括当前实现的“for循环”语法,以及被注释掉的“forEach”语法。

两个主要问题:

1) 每个名字前面的数字是我的 for 循环中的“i”。为什么这个“i”不是从 0 到 10 的顺序?我如何让它这样做?每次运行代码时,它的顺序似乎都不同。并且,它会在每次新的迭代中重复之前循环的数字。我想了解为什么会这样。

2) 代码似乎出现故障。在console.log中可以看到意外的行为——for循环在一个循环中输出console.log的前两行,然后跳出console.logs测试变量“a”和for循环下面的其他文本,然后跳回到 for 循环和 console.logs 函数的输出。我在谷歌浏览器中查看控制台,我确实读到控制台可能存在时间不一致,但我不明白循环是如何被分成两半的——前两行,然后是函数在后面的代码之后记录调用。

遍历数组的最佳方法是什么?非常感谢您对如何正确调用循环中的函数或您可以提供的资源的任何见解。

$("document").ready(function(){

  var friends = ["lainzero", "freecodecamp", "storbeck", "terakilobyte", "habathcx","RobotCaleb","thomasballinger","noobs2ninjas","beohoff", "dtphase", "MedryBW"];
  var html = "";
  var url = "";

  function getStreamingData(eachfriend, number) {
     url = "https://api.twitch.tv/kraken/streams/"+eachfriend;

  $.ajax({
  dataType: "jsonp",
  url: url,
  success: function(result) {
      console.log(result+", "+result.stream);

    if(result.stream !== null) {
      html+= "<li class='streaming'><a href='twitch.tv/"+eachfriend+"'>"+number+": "+eachfriend;
      html +="<i class='fa fa-play-circle style='font-size:20px;color:green;''></i>";
    } else if (result.stream === null) {
      html+= "<li class='not_streaming'><a href='twitch.tv/"+eachfriend+"'>"+number+": "+eachfriend;
      html +="<i class='fa fa-stop-circle' style='font-size:20px;color:red;'></i>";
    }
     html +="</a></li>";
    $("#all ul").append(html);

    }//success
  });//$ajax
}//getstreamingdata function


for (var i=0;i<friends.length;i++) {
  console.log(i);
  console.log(friends[i]);
  getStreamingData(friends[i], i);
} 

//Same as for loop above, but using forEach. This produces the same results.
/*
var i=0;
friends.forEach(function(friend) { 
   getStreamingData(friend, i);
   i++;
});    
  */

  var a = 4;//testing console output
  console.log(a);
  console.log("why is this showing up before the getStreamingData function's console output?");
  console.log("but it's showing up after the console.log(i) and console.lg(friends[i]) output? So this section is interupting the for loop above");
  console.log(" and why is the for loop out of order and repeating itself?");

 });//doc ready

【问题讨论】:

    标签: javascript loops for-loop foreach


    【解决方案1】:

    您正在循环中执行异步任务。您不应该期望这些异步任务按照它们开始的顺序完成。

    函数getStreamingData就是我要说的那个。

    相关:Asynchronous for cycle in JavaScript

    这是我很久以前写的一个sn-p,我还在小项目中使用它。然而,有很多图书馆可以做同样的事情,而且还有更多。

    Array.prototype.forEachAsync = function (cb, end) {
        var _this = this;
        setTimeout(function () {
            var index = 0;
            var next = function () {
                if (this.burned) return;
                this.burned = true;
                index++;
                if (index >= _this.length) {
                    if (end) end();
                    return;
                }
                cb(_this[index], next.bind({}));
            }
            if (_this.length == 0) {
                if (end) end();
            }else {
                cb(_this[0], next.bind({}));
            }
        }, 0);
    }
    

    像这样触摸prototype 不是一个好习惯。但只是为了让你知道如何做到这一点...... 在该代码之后,您可以异步循环数组。完成一个元素后,请致电next

    var array = [1, 2, 3, 4]
    array.forEachAsync(function (item, next) {
        // do some async task
        console.log(item + " started");
        setTimeout(function () {
            console.log(item + " done");
            next();
        }, 1000);
    }, function () {
        console.log("All done!");
    });
    

    【讨论】:

      猜你喜欢
      • 2023-01-25
      • 1970-01-01
      • 2012-05-26
      • 2014-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      相关资源
      最近更新 更多