gpt4 book ai didi

javascript - 数组保持随机顺序输出 - Push

转载 作者:行者123 更新时间:2023-11-28 19:07:10 25 4
gpt4 key购买 nike

我似乎无法弄清楚这一点。

首先,我使用 radio 列表调用 API,然后检查 API 中存在多少个 radio 。

然后,我根据 radio.length 的长度使用“for 循环”调用另一个 API,并将数据推送到数组中。

这是我使用(Angular JS)的代码

var radioShows = [];

$http.get('http://api.example.com/radios/').success(function(results) {

var totalRadioLength = [];

for (i = 0; i <= results.length; i++) {

totalRadioLength.push(i);
console.log(totalRadioLength) // Outputs 7

$http.get('http://api.example.com/radioshows/fr/radio/' + results[i].id + '/?day=' + x + '').success(function(resultShows) {

if (resultShows.success === false) {
// console.log('No')
} else {
// console.log('Yes')
radioShows.push(resultShows);

}
})
}
})

这似乎工作正常,除了我的数组 radioShows 每次都以随机顺序出现。根据第一个 API 调用的顺序输出数组的最佳方法是什么?

最佳答案

您以不可预测的顺序获得结果的原因是您按照响应到达的顺序将它们放入数组中,并且不能保证请求按照您发送它们的顺序完成。根据输入数据的索引将结果放入数组中。您可以使用函数创建一个作用域,其中每次迭代都会获取自己的变量i:

for (i = 0; i <= results.length; i++) {

(function(i){

totalRadioLength.push(i);
console.log(totalRadioLength) // Outputs 7

$http.get('http://api.example.com/radioshows/fr/radio/' + results[i].id + '/?day=' + x + '').success(function(resultShows) {

if (resultShows.success === false) {
// console.log('No')
} else {
// console.log('Yes')
radioShows[i] = resultShows;
}

});

})(i);

}

关于javascript - 数组保持随机顺序输出 - Push,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31440007/

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