为什么我会得到一个不同的阵列? [英] Why do I get a different array?

查看:76
本文介绍了为什么我会得到一个不同的阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天。
我有给出不同数组的问题;

Good day. I have problem with give different arrays;

我的代码接下来:

setInterval(function() {

var TestName = [];
var requests = [];
TestName.push('0');
for($i=1; $i<8; $i++) {
    var id = $i;
    requests.push($.post("./Scripts/", {
    record:id,
    opt:'get_test'
    }, function(data){
          TestName.push(data);
    }));
}

 $.when.apply($,requests).done(function(){

     for($i=1; $i<8; $i++) {
$('#test'+$i).html('').html(TestName[$i]);

}
alert(TestName);
 });

}, 15000);

此代码可以工作,但每次我得到不同的数组...

This code works but every time I get different arrays...

例如:

alert(TestName); 结果一:

0,
<a href="#"><img src="./images/test1.png"></a>,
<a href="#"><img src="./images/test2.png"></a>,
<a href="#"><img src="./images/test3.png"></a>,
<a href="#"><img src="./images/test4.png"></a>,
<a href="#"><img src="./images/test5.png"></a>,
<a href="TestTestTestTestTest.php"><img src="./1358997710.jpg"></a>,
<a href="#"><img src="./images/test7.png"></a>,

alert(TestName); 结果二:

0,
<a href="#"><img src="./images/test1.png"></a>,
<a href="#"><img src="./images/test2.png"></a>,
<a href="TestTestTestTestTest.php"><img src="./1358997710.jpg"></a>,
<a href="#"><img src="./images/test3.png"></a>,
<a href="#"><img src="./images/test5.png"></a>,
<a href="#"><img src="./images/test4.png"></a>,
<a href="#"><img src="./images/test7.png"></a>

正如您可以在每次交换座位时看到数组的元素,有时排列数组的元素订单错误。

As you can see elements of the array each time exchange seats, and sometimes elements of the array are arranged in the wrong order.

请告诉我代码中可能出错的地方?

Tell me please where may be been error in code?

推荐答案

每次数组不同的原因是您正在运行异步请求,然后从回调中填充。每次执行此操作时,您的请求都会以不同的顺序完成,因此会以不同的顺序填充数组。

The reason your array is different each time is that you are running asynchronous requests and then populating from the callback. Each time you do this your requests happen to be finishing in different order and therefore populating the array in a different order.

您不能依赖于调用的异步请求回调在执行过程中的任何特定点,可以随时调用它们,具体取决于响应何时返回。

You must not rely on async request callbacks being called at any particular point within your execution, they can be called at any time, depending on when the response decides to come back.

这篇关于为什么我会得到一个不同的阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆