数组调用JSON函数报错:Twitch直播状态批量检测功能异常
解决Twitch主播批量在线状态检测的异常问题
嘿,这问题我太熟啦!你遇到的是异步请求和JavaScript作用域的经典坑,咱们来一步步拆解:
问题根源
你用var声明的循环变量i是全局作用域的,而$.getJSON是异步请求——当回调函数执行时,for循环早就跑完了,i的值已经变成了数组的长度(也就是4),这时候twitchChannels[i]自然就是undefined,所以才会出现截图里的异常。
三种解决方案
方案1:用let代替var(最简单,ES6+支持)
把循环里的var i改成let i,这样每次循环都会创建一个独立的作用域,回调函数能拿到当前循环的正确索引:
function test() { var twitchChannels = ["imaqtpie", "summit1g", "tyler1", "greekgodx"]; // 用let声明i,让每个循环都有独立作用域 for (let 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"; } }); } }
方案2:用forEach遍历数组(更直观)
直接遍历数组里的每个主播名称,不需要管索引,每个元素都在独立的回调作用域里:
function test() { var twitchChannels = ["imaqtpie", "summit1g", "tyler1", "greekgodx"]; twitchChannels.forEach(function(channelName) { console.log(channelName); $.getJSON('https://api.twitch.tv/kraken/streams/' + channelName + '?client_id=XXXX', function(channel) { console.log(channelName); if (channel.stream == null) { console.log("Offline: " + channelName) document.getElementById(channelName).style.backgroundColor = "red"; } else { console.log("Online: " + channelName) document.getElementById(channelName).style.backgroundColor = "green"; } }); }); }
方案3:立即执行函数(IIFE,兼容旧浏览器)
如果你的项目需要兼容不支持ES6的旧浏览器,可以用立即执行函数把当前的i值绑定到独立作用域里:
function test() { var twitchChannels = ["imaqtpie", "summit1g", "tyler1", "greekgodx"]; for (var i = 0; i < twitchChannels.length; i++) { // 用IIFE保存当前循环的i值 (function(currentIndex) { console.log(currentIndex + " " + twitchChannels[currentIndex]); $.getJSON('https://api.twitch.tv/kraken/streams/' + twitchChannels[currentIndex] + '?client_id=XXXX', function(channel) { console.log(currentIndex + " " + twitchChannels[currentIndex]); if (channel.stream == null) { console.log("Offline: " + twitchChannels[currentIndex]) document.getElementById(twitchChannels[currentIndex]).style.backgroundColor = "red"; } else { console.log("Online: " + twitchChannels[currentIndex]) document.getElementById(twitchChannels[currentIndex]).style.backgroundColor = "green"; } }); })(i); } }
小建议
- 可以给
$.getJSON加上错误处理(比如.fail()方法),防止API请求失败导致页面状态不更新; - Twitch的Kraken API是旧版接口,现在官方推荐使用Helix API,如果你后续有升级需求可以去看看官方文档。
内容的提问来源于stack exchange,提问作者Pretpacked
相关产品推荐
相关产品推荐

