【问题标题】:Array gives errors after JSON function数组在 JSON 函数后给出错误
【发布时间】:2018-07-07 08:35:24
【问题描述】:

我正在尝试检查抽搐流是在线还是离线,如果是,请更改背景颜色。如果我在没有数组的情况下检查并且只输入它可以工作的名称,但使用数组它不会(我对 JSON 了解不多)。

function test() {
  var twitchChannels = ["imaqtpie", "summit1g", "tyler1", "greekgodx"];

  for (var i = 0; i < twitchChannels.length; i++) {
    console.log(i + " " + twitchChannels[i]);

    $.getJSON('https://api.twitch.tv/kraken/streams/' + twitchChannels[i] + '?client_id=XXXX', function(channel) {
      console.log(i + " " + twitchChannels[i]);

      if (channel["stream"] == null) {
        console.log("Offline: " + twitchChannels[i])
        document.getElementById(twitchChannels[i]).style.backgroundColor = "red";
      } else {
        console.log("Online: " + twitchChannels[i])
        document.getElementById(twitchChannels[i]).style.backgroundColor = "green";
      }

    });
  }

}

错误:红色部分内的http://prntscr.com/i6qj51是json函数内部发生的事情

【问题讨论】:

标签: javascript json twitch


【解决方案1】:

你的代码很弱,因为你没有管理你所做的每一次得到的callback 。 你也没有检查:

document.getElementById(twitchChannels[i])

为空,因为异常清楚地表明您无法获取:

.style.backgroundColor

从无到有。

基本检查 VanillaJS:

if(!document.getElementById("s"))
  console.log('id ' + twitchChannels[i] +  ' not found in dom')
else 
  console.log('id ' + twitchChannels[i] +  ' found in dom')

同时考虑将 JQuery 与 VanillaJS 混合使用是非常糟糕的做法;使用正确的 JQuery 方法访问dom element by ID

【讨论】:

  • 您的回答不包含如何解决问题的任何信息。
  • 添加逻辑来测试 dom VanillaJS
  • “将 JQuery 与 VanillaJS 混合非常糟糕的做法”:如果你知道自己在做什么,这根本不是坏做法。
  • 在给定的代码中document.getElementById(twitchChannels[i]) 将始终返回null。测试document.getElementById(twitchChannels[i]) 是否为null 是一种很好的做法,但它并不能解决问题。
  • @AngelPolitis:这是有争议的。对于我在大项目中的经验,这应该会导致很大的问题。尤其是长期的。 t.niese:jsfiddle.net/Black_Jack/LsL3pmLm/1
【解决方案2】:

您应该将 twitchChannel 传递给该函数,因为 var i 正在改变,这与其他已经提到的问题一样:Preserving variables inside async calls called in a loop.

【讨论】:

  • 循环中的测试是 less then_(&lt;) 而不是 _less or equal then (&lt;=),所以 twitchChannels.length-1 是错误的。跨度>
【解决方案3】:

问题是您在 cicle 中进行了一些 ajax 调用,但 ajax 调用是异步的。

当您收到第一个响应时,cicle 已经完成,并且 i==4,超出了 twitchChannels 大小:这就是您在控制台上显示“4 undefined”的原因。

您可以通过以下方式更改您的代码:

function test() {
    var twitchChannels = ["imaqtpie", "summit1g", "tyler1", "greekgodx"];

    for (var i = 0; i < twitchChannels.length; i++) {
        executeAjaxCall(twitchChannels[i]);
    }
}
function executeAjaxCall(twitchChannel){
    $.getJSON('https://api.twitch.tv/kraken/streams/' + twitchChannel + '?client_id=XXXX', function(channel) {
        console.log(twitchChannel);

        if (channel["stream"] == null) {
            console.log("Offline: " + twitchChannel)
            $('#'+twitchChannel).css("background-color", "red");
        } else {
            console.log("Online: " + twitchChannel)
            $('#'+twitchChannel).css("background-color", "green");
        }

    });
    }
}

【讨论】:

    【解决方案4】:

    在回调函数内部调用console.log(i + " " + twitchChannels[i]);时,变量i已经设置为4,访问数组twitchChannels的第4个元素会得到undefined,因为数组只有4个元素。

    这是因为$.getJSON 是一个简写的Ajax 函数,顾名思义,它异步地 执行您的请求。所以实际发生的是,根据您提供的输出,

    1. 循环执行4次,发送了4个Ajax请求。
    2. 循环退出; i 现在已经设置为 4。
    3. ajax 请求返回;回调被调用,但他们看到的 i 值现在是 4。

    您可以将回调中的console.log 更改为console.log(i + " " + twitchChannels[i] + " (inside callback)"); 之类的内容,以便更清楚地看到这一点。

    i的当前值绑定到闭包上,可以得到正确的结果。

    function test() {
      var twitchChannels = ["imaqtpie", "summit1g", "tyler1", "greekgodx"];
    
      function make_callback(index) {
        return function (channel) {
            console.log(index + " " + twitchChannels[index]);
    
            if (channel["stream"] == null) {
              console.log("Offline: " + twitchChannels[index])
              document.getElementById(twitchChannels[index]).style.backgroundColor = "red";
            } else {
              console.log("Online: " + twitchChannels[index])
              document.getElementById(twitchChannels[index]).style.backgroundColor = "green";
            }
        }
      }
    
      for (var i = 0; i < twitchChannels.length; i++) {
        console.log(i + " " + twitchChannels[i]);
    
        $.getJSON('https://api.twitch.tv/kraken/streams/' + twitchChannels[i] + '?client_id=XXXX', make_callback(i));
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-11
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 2018-06-13
      • 2017-10-20
      • 1970-01-01
      相关资源
      最近更新 更多