控制台的奇怪行为 - 仅在首次加载网站时记录数组

时间:2016-07-01 18:27:34

标签: javascript arrays console append

大家好,

我从事一个简单的项目,javascript的工作是:

  1. 使用for循环从twitch(使用jsonp)获取数据多次,添加必要的html并将其推送到数组。
  2. 当循环完成后,我想要添加到网站的数组中的所有预先安排的html,再次使用for循环(其中有三个 - 因为有三个数组),如下所示):

    for (var i = 0; i < newItemBoxOn.length; i++) {
     $("#container").append(newItemBoxOn[i]); 
        }
    
  3. 但它没有用。所以我尝试了console.log所有三个数组。 当我加载整个网站时,我注意到控制台的不同行为(这是我得到的): enter image description here

    如您所见,控制台中有三个阵列。但是,当我刷新网站时,我得到了三个空(!)数组。

    enter image description here

    1.为什么会这样? 2.如何正确地将数组的值附加到网站?

    指向codepen的链接:https://codepen.io/RycerzPegaza/pen/AXRdGa

    很高兴,非常感谢你提出好的建议,我希望我能很好地描述这个问题

2 个答案:

答案 0 :(得分:0)

$(document).ready(function() {
    var link = "https://api.twitch.tv/kraken/streams/";
    var channelsArr = ["ESL_SC2", "OgamingSC2", "comster404", "cretetion", "freecodecamp", "brunofin", "storbeck", "sheevergaming", "RobotCaleb", "noobs2ninjas", "terakilobyte", "syndicate", "pewdiepie", "riotgames"];
    var newItemBoxClosed = [];
    var newItemBoxOn = [];
    var newItemBoxOff = [];
    for (var i = 0; i < channelsArr.length; i++) {
      var currentLink = link + channelsArr[i] + "?callback=?";
      $.getJSON(currentLink, function(data) {
          // do something with the data;
          if (data.status === 422) {
            newItemBoxClosed.push("<div class='item-box'><ul><li><div class='profile-img'><div class='cross'></div><img src=''></div></li><li><div class='status-light' id='light-red'><p>off</p></div></li></ul><div class='reflection'></div><div class='username'></div><div class='userstatus'>channel closed</div></div>");
          }
          // item-box massive production
          else {
            $.getJSON(data["_links"].channel + "?callback=?", function(channelData) {
                // if data.stream === null - there's no streaming
                if (data.stream === null) {
                  newItemBoxOff.push("<div class='item-box'><ul><li><div class='profile-img'><img src='" + channelData.logo + "'></div></li><li><div class='status-light' id='light-red'><p>off</p></div></li></ul><div class='reflection'></div><div class='username'>" + channelData.display_name + "</div><div class='userstatus'>offline</div></div>");
                }
                // if data.stream !== null - stream is live
                else {
                  newItemBoxOn.push("<div class='item-box'><ul><li><div class='profile-img'><img src='" + channelData.logo + "'></div></li><li><div class='status-light' id='light-green'><p>on</p></div></li></ul><div class='reflection'></div><div class='username'>" + channelData.display_name + "</div><div class='userstatus'>" + channelData.game + ": " + channelData.status + "</div></div>");
                }
                newItemBoxOn.forEach(function(item) {
                  $(container).append($(item));
                });

              }) // end inner json
          }
        }) // end  getJSON
    } // end for loop

  }) // end ready
/* colorset: 
grey - #D1D1D1;
purple - #6441A5;
*/

/*don't know if media queries needed if i have flexbox */

#container {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;
  height: 99%;
}
@media screen and (max-width: 570px) {
  #switch {
    transform: translateX(5%);
  }
}
/* fonts */

body {
  background-color: #D1D1D1;
  font-family: 'Dosis', sans-serif;
  color: #6441A5;
}
#header {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  height: 35px;
  margin: 6px 0 15px;
  padding: 0;
}
#switch {
  height: 36px;
  width: 100px;
  position: relative;
  padding: 0px 5px;
  transform: translate(24%, 6%);
  font-family: 'Bungee Shade';
  font-size: 0.77em;
  text-align: center;
  line-height: 35px;
  font-weight: bold;
  color: #444;
}
#switch-on,
#switch-on:active {
  width: 48%;
  height: 100%;
  background: #44C947;
  display: inline-block;
  margin: 0;
  padding: 0;
  cursor: pointer;
  box-shadow: 2px 2px 1px #555;
}
#switch-on:active {
  background: #33B836;
  transform: translate(2%, 4%);
  box-shadow: 0 1px #999;
}
#switch-off,
#switch-off:active {
  width: 48%;
  height: 100%;
  background: #E02443;
  display: inline-block;
  margin: 0;
  padding: 0;
  cursor: pointer;
  box-shadow: 2px 2px 1px #555;
}
#switch-off:active {
  background: #D01332;
  transform: translate(2%, 4%);
  box-shadow: 0 1px #999;
}
#title-bar {
  width: 329px;
  height: 35px;
  border: 2px solid purple;
  margin: 1px auto 4px;
  transform: translateX(-1px);
  -webkit-box-shadow: 2px 2px 2px #888;
  -moz-box-shadow: 2px 2px 2px #888;
  box-shadow: 2px 2px 2px #888;
  position: relative;
}
.item-box {
  width: 160px;
  height: 250px;
  border: 2px solid purple;
  margin-right: 2px;
  margin-bottom: 4px;
  -webkit-box-shadow: 4px 5px 3px -1px rgba(0, 0, 0, 0.3);
  -moz-box-shadow: 4px 5px 3px -1px rgba(0, 0, 0, 0.3);
  box-shadow: 4px 5px 3px -1px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  position: relative;
}
li {
  list-style-type: none;
  display: inline-block;
}
.profile-img {
  -webkit-clip-path: polygon(25% 0%, 50% 2%, 75% 15%, 95% 50%, 82% 80%, 70% 90%, 25% 93%, 4% 60%, 5% 37%);
  background: rgba(0, 0, 0, 0.4);
  background-size: 50px 50px;
  height: 100px;
  width: 100px;
  margin: 1px auto;
  transform: translate(-10px, -10px);
  position: absolute;
  z-index: 1;
}
.status-light {
  width: 10px;
  height: 10px;
  border-radius: 100%;
  transform: translate(95px, 1px);
  box-shadow: 0px 0px 1px rgba(10, 10, 10, 0.8);
}
p {
  font-size: 0.62em;
  line-height: 32px;
  transform: translate(-4px, 2px);
  font-family: 'Bungee Shade';
}
#light-red {
  background: #E02443;
}
#light-green {
  background: #44C947;
}
.username,
.userstatus {
  display: block;
  width: 90%;
  margin: 1px auto;
  color: #6441A5;
  font-size: 1em;
  -webkit-transform: translate(0px, 78px);
  padding: 2px 0px;
  text-align: center;
}
.reflection {
  position: absolute;
  -webkit-clip-path: polygon(25% 10%, 50% 2%, 75% 15%, 95% 50%, 82% 80%, 70% 70%, 75% 100%, 10% 79%, 5% 75%, 2% 60%, 4% 72%, 0% 45%, 0% 40%, 4% 34%);
  height: 300px;
  width: 300px;
  background: rgba(100, 65, 165, 0.12);
  transform: translate(0px, -50px);
}
.username {
  border: 1px solid #6441A5;
}
.userstatus {
  font-size: 0.9em;
  font-weight: bold;
  margin: 5px auto;
}
img {
  width: inherit;
  height: inherit;
  box-shadow: 1px 2px 5px black;
}
h1 {
  font-family: 'Bungee Shade';
  font-size: 1.4em;
  margin: 0 auto;
  text-align: center;
  transform: translateY(-13px);
}
/*** red cros ***/

.cross {
  position: absolute;
  right: 68px;
  opacity: 1;
}
.cross:before,
.cross:after {
  position: absolute;
  left: 15px;
  content: ' ';
  height: 105px;
  width: 2px;
  background-color: #E02443;
}
.cross:before {
  transform: rotate(45deg);
}
.cross:after {
  transform: rotate(-45deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="header">
    <div id="switch">
      <div id="switch-on">on</div>
      <div id="switch-off">off</div>
    </div>
    <div id="title-bar">
      <h1>twitch observer</h1>
    </div>
  </div>
  <div id="container">
    <!-- container start -->


  </div>
  <!-- container end -->
</body>

您正在对Web服务进行异步调用。这正是第二个JSON调用嵌套在第一个中的原因。我更改了您的JavaScript以将console.log()调用放入其中,然后获得大量有效的HTML,类似于:

["<div class='item-box'><ul><li><div class='profile-…div class='userstatus'>channel closed</div></div>", "<div class='item-box'><ul><li><div class='profile-…div class='userstatus'>channel closed</div></div>"]
0
:
"<div class='item-box'><ul><li><div class='profile-img'><div class='cross'></div><img src=''></div></li><li><div class='status-light' id='light-red'><p>off</p></div></li></ul><div class='reflection'></div><div class='username'></div><div class='userstatus'>channel closed</div></div>"
1
:
"<div class='item-box'><ul><li><div class='profile-img'><div class='cross'></div><img src=''></div></li><li><div class='status-light' id='light-red'><p>off</p></div></li></ul><div class='reflection'></div><div class='username'></div><div class='userstatus'>channel closed</div></div>"
length
:
2

修改 要将该HTML实际插入到容器div中,您将在第二个JSON调用中迭代该数组:

newItemBoxOn.forEach(function (item) {
  $(container).append($(item));
});

答案 1 :(得分:0)

$.when().then()Function.prototype.apply()代替for循环

的方法
$(document).ready(function() {
    var link = "https://api.twitch.tv/kraken/streams/";
    var channelsArr = ["ESL_SC2", "OgamingSC2", "comster404", "cretetion", "freecodecamp", "brunofin", "storbeck", "sheevergaming", "RobotCaleb", "noobs2ninjas", "terakilobyte", "syndicate", "pewdiepie", "riotgames"];
    var newItemBoxClosed = [];
    var newItemBoxOn = [];
    var newItemBoxOff = [];
    var dfd = new $.Deferred();
    // for (var i = 0; i < channelsArr.length; i++) {
    $.when.apply($, $.map(channelsArr, function(_, i) { 
      var currentLink = link + channelsArr[i] + "?callback=?";
      return $.getJSON(currentLink, function(data) {
          // do something with the data;
          if (data.status === 422) {
            newItemBoxClosed.push("<div class='item-box'><ul><li><div class='profile-img'><div class='cross'></div><img src=''></div></li><li><div class='status-light' id='light-red'><p>off</p></div></li></ul><div class='reflection'></div><div class='username'></div><div class='userstatus'>channel closed</div></div>");
          }
          // item-box massive production
          else {
            return $.getJSON(data["_links"].channel + "?callback=?", function(channelData) {
                // if data.stream === null - there's no streaming
                if (data.stream === null) {
                  newItemBoxOff.push("<div class='item-box'><ul><li><div class='profile-img'><img src='" + channelData.logo + "'></div></li><li><div class='status-light' id='light-red'><p>off</p></div></li></ul><div class='reflection'></div><div class='username'>" + channelData.display_name + "</div><div class='userstatus'>offline</div></div>");
                }
                // if data.stream !== null - stream is live
                else {
                  newItemBoxOn.push("<div class='item-box'><ul><li><div class='profile-img'><img src='" + channelData.logo + "'></div></li><li><div class='status-light' id='light-green'><p>on</p></div></li></ul><div class='reflection'></div><div class='username'>" + channelData.display_name + "</div><div class='userstatus'>" + channelData.game + ": " + channelData.status + "</div></div>");
                }

              }) // end inner json
          }
        })
        // end  getJSON
    })) // end for loop
    .then(function(data) {
      $("body").append(newItemBoxOn, newItemBoxOff, newItemBoxClosed)
    })
  }) // end ready

plnkr https://plnkr.co/edit/hlquTnwurSuN2SxnT0UI?p=preview