gpt4 book ai didi

javascript - For 循环和 ForEach 循环在 getJSON 中表现出不同的行为

转载 作者:行者123 更新时间:2023-11-30 11:32:03 25 4
gpt4 key购买 nike

我正在尝试从 api 获取数据,但我使用的 For 循环在嵌套的 GetJSON 调用中返回具有空值和未定义值的对象,但是当我尝试 forEach 循环时它工作正常。 有什么想法吗?

var baseUrl = "https://wind-bow.gomix.me/twitch-api/";
var channels = ["ESL_SC2", "FreeCodeCamp", "Test_channel", "brunofin"];

//**First function with forEach. WORKS FINE**
function getDataForEach() {

channels.forEach(function(channel) {

$.getJSON(txtUrl('streams', channel), function(json) {
console.log(json);

$.getJSON(txtUrl('channels', channel), function(json2) {
console.log(json2);

});
});

});
}

//**Second function with a normal for loop. The 2nd JSON doesnt return the proper data**

function getDataForLoop() {
for (i=0;i<channels.length;i++){
$.getJSON(txtUrl('streams', channels[i]), function(json) {
console.log(json);

//THIS 2nd call doesnt returns undefined objects.
$.getJSON(txtUrl('channels', channels[i]), function(json2) {
console.log(json2);

});
});

});
}

function txtUrl(prop, chnl) {
return baseUrl + prop + '/' + chnl + '?callback=?';
}

$(document).ready(function() {
getData();
});

最佳答案

getJSON 是异步的,所以它的回调函数不会立即执行,因此在 for 循环的情况下它会产生 this error如果您在回调中使用 i

我注意到的另一件事是您使用全局 i 这也是一个 source of troubles .

如果您使用的是 ECMAScript 6,则可以使用 let 来声明 i:

for(let i = 0; ...)

let 是 block 作用域的,因此使用它不会产生上面第一个链接中的错误。

关于javascript - For 循环和 ForEach 循环在 getJSON 中表现出不同的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45867592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com