简体   繁体   English

了解forEach和javascript之间的区别

[英]Understanding difference between forEach and for in javascript

I am coding an app using twitch.tv API, for which i need to make multiple getJSON() calls for different users. 我正在使用twitch.tv API编写应用程序,为此我需要为不同的用户进行多个getJSON()调用。 Is there any explanation for the following output. 以下输出是否有任何解释?

//users array contains the list of users for which data is fetched
var users = ["freecodecamp", "brunofin", "storbeck", "medrybw", "comster404", "terakilobyte", "habathcx","RobotCaleb","thomasballinger","noobs2ninjas","beohoff"];

When using the simple for loop: 使用简单的for循环时:

for (var i = 0; i < users.length; i++) {
            var user = users[i];
            $.getJSON("https://api.twitch.tv/kraken/streams/" + user + "?callback=?", function(json) {
                var add = user;
                if(json.status === 422) {
                    add = add + ' ' + "Closed";
                } else {
                    if (json.stream === null) {
                        add = add + ' ' + "Offline";
                    } else {
                        add = add + ' ' + json.stream.game;
                    }
                }
                $("#userList").append("<div>" + add + "</div>");
            });
};

Output: 输出:

beohoff Closed
beohoff Offline
beohoff Offline
beohoff Offline
beohoff StarCraft: Brood War
beohoff Offline
beohoff Offline
beohoff Offline
beohoff Offline 
beohoff Closed
beohoff Offline

When using forEach: 使用forEach时:

users.forEach(function(user) {
            $.getJSON("https://api.twitch.tv/kraken/streams/" + user + "?callback=?", function(json) {
                var add = user;
                if(json.status === 422) {
                    add = add + ' ' + "Closed";
                } else {
                    if (json.stream === null) {
                        add = add + ' ' + "Offline";
                    } else {
                        add = add + ' ' + json.stream.game;
                    }
                }
                $("#userList").append("<div>" + add + "</div>");
            });
});

Output: 输出:

brunofin Closed
comster404 Closed
storbeck Offline
terakilobyte Offline
freecodecamp Offline
medrybw StarCraft: Brood War
thomasballinger Offline
RobotCaleb Offline
noobs2ninjas Offline
habathcx Offline
beohoff Offline

Are the ajax calls made sequentially in case of forEach or is there something else ? 在forEach的情况下,ajax调用是顺序进行的还是其他方法?

With for (var i = 0; i < users.length; i++)) { ... } , you subsequently assign values 0 till users.length-1 to i and do something with it, but you stay in the same closure. 使用for (var i = 0; i < users.length; i++)) { ... } ,您随后将值0分配给i直到users.length-1并对其进行了处理,但您仍处于同一闭包中。

Due to the asynchronous nature of js, you send all your json requests before receiving the first answer. 由于js的异步特性,您在收到第一个答案之前先发送所有json请求。 When your answers arrive, user has value users[users.length-1] and this is then used in all your output. 当您的答案到达时, user具有值users[users.length-1] ,这将在所有输出中使用。

With users.forEach(function(user) { ... } , you create a new closure for each element of users. In each closure, you have a local user variable which you will use when the response of your json request arives. 使用users.forEach(function(user) { ... } ,为用户的每个元素创建一个新的闭包,在每个闭包中,都有一个本地user变量,将在json请求的响应到达时使用。

when you iterate with for loop and running async code in it's scope, when the first return of the Ajax, the iteration is already over. 当您使用for循环进行迭代并在其范围内运行异步代码时,当Ajax首次返回时,迭代已经结束。

with forEach loop you run a callback for each iteration creating a new socpe, and even the iteration are over, each function is now at the event loop waiting to be invoked. 使用forEach循环,您可以为每次迭代运行一个回调,从而创建一个新的socpe,甚至迭代已经结束,每个函数现在都在事件循环中等待被调用。

you can do something like this so it will be the same: 您可以执行以下操作,使其保持不变:

for (var i = 0; i < users.length; i++) {
    getUser(user[i]);
};

function getUser(user){
  $.getJSON("https://api.twitch.tv/kraken/streams/" + user + "?callback=?", function(json) {
      var add = user;
      if(json.status === 422) {
          add = add + ' ' + "Closed";
      } else {
          if (json.stream === null) {
              add = add + ' ' + "Offline";
          } else {
              add = add + ' ' + json.stream.game;
          }
      }
      $("#userList").append("<div>" + add + "</div>");
  });
}

best way to understand it is by looping with setTimeout and print i: 理解它的最好方法是通过循环setTimeout并打印i:

for(var i = 0; i < 10; i++){
    setTimeout(function(){ console.log(i) }, 100);
};

which will output: 10 ten times, and run it a function: 它将输出:10十次,并运行一个函数:

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

function log(i){ setTimeout(function(){ console.log(i)}, 100) };

hope it was helpful. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM