JavaScript getJSON在数组中返回重复值

时间:2017-02-16 23:44:35

标签: javascript jquery arrays json

我正在尝试解析json结果,但我在数组中不断获取重复值。好像代码运行了两次。这是我的代码任何反馈将不胜感激

var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas", "brunofin", "comster404"]
var clientID = "######";
var allChannels = [];
var feedReturn = [];
$(document).ready(function() {
    for (var i = 0; i < channels.length; i++) {
        allChannels[i] = channels[i];
        //allChannels[i][0] = channels[i]
        $.getJSON("https://api.twitch.tv/kraken/streams/" + channels[i] + "?
            client_id = sbp1wnku2j32dtnjj4qefhslopxq8s ",function(data){
            $.each(data, function(i) {
                if (data.stream == null) {
                    feedReturn.push(["Null", data._links.channel]);
                } else {
                    feedReturn.push(["Not Null", data._links.channel]);
                }
                //console.log(data.stream);
                // console.log(data._links.channel);
                //feedReturn.push(data.stream,data._links.channel);
            })
        })
}
});
console.log(feedReturn);

1 个答案:

答案 0 :(得分:1)

您正在$.each()对象上调用data,该对象将返回一个长度等于该对象上属性数的数组。由于返回的API数据有两个属性(_links,stream),因此对于每个API调用,它将运行.push() 2次。只需删除$.each()即可解决阵列中重复记录的问题。

$.getJSON("https://api.twitch.tv/kraken/streams/"+channels[i]+"?client_id=sbp1wnku2j32dtnjj4qefhslopxq8s",function(data){
  if(data.stream == null){

    feedReturn.push(["Null",data._links.channel]); 

  } else {

    feedReturn.push(["Not Null",data._links.channel]);
  }
});