无法读取数组中的对象

时间:2017-12-23 12:52:56

标签: javascript arrays json object

我从数组中读取对象时遇到问题。我可以使用console.log(objArr),但是console.log(objArr [0])= undefined。 pic from codepen

var arr = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var content = document.querySelector(".content");
var objArr = [];


  arr.forEach(function(data, index){
    $.getJSON("https://wind-bow.gomix.me/twitch-api/streams/" + data + "?callback=?", function(info) {
    if(info.stream){
              objArr.push({
            name: data,
            status: "online",
            link: info._links.channel,
            game: info.stream.game
              });
   } else{
              objArr.push({
            name: data,
            status: "offline",
            link: info._links.channel,
            game: "offline"
              });
    }
   });
  })

console.log(objArr[0]);

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我认为你的console.log过早被调用。要让json需要一些时间。尝试将你的日志放在if(info.stream){} else {}

之后