简体   繁体   English

为什么循环下面的语句在循环终止之前执行

[英]why does statement below loop executes before termination of loop

I was wondering why do i get alert before printing all vlaues 我想知道为什么在打印所有vlaues之前我会收到警报

<script>
    for(var i=0; i<=1000; i++)
    {
        console.log(i);
    }
    alert('Hello');
</script>

Well it is not executing before loop, it is executing correctly. 好吧,它不是在循环之前执行,而是在正确执行。

Your console may be refreshing little late. 您的控制台可能刷新得有点晚。

alert() will block your browser whilst waiting to be dismissed by the user . alert()将在阻止用户浏览器的同时阻止您的浏览器

Maybe they haven't been written to the console yet by the time the alert appears. 警报出现时,可能尚未将它们写入console It depends on what your console object is. 这取决于您的console对象是什么。

BTW, they appear fine in the console before the alert in my Chrome 10 on OS X. 顺便说一句,在OS X上我的Chrome 10中,在警报出现之前,它们在控制台中看起来还不错。

The console is lagging behind. 控制台落后。 The loop is executed first. 循环首先执行。 This shows it better: 这显示得更好:

var t = [];
for(var i=0; i<=1000; i++)
{
    t.push(i);
}
console.log(t.length);
alert('Hello');

How are you executing this? 您如何执行此操作? My console doesn't show the alert until all the numbers are displayed. 在显示所有数字之前,我的控制台不会显示警报。 Yours must be lazily rendering output. 您必须懒惰地渲染输出。 So the loop does finish before the alert, but the log was only written to a buffer. 因此,循环确实在警报之前完成,但日志仅写入了缓冲区。

<script>
INSTRUCTION A;
INSTRUCTION B;
INSTRUCTION C;
</script>

In javascript the execution of INSTRUCTION B is not dependent upon completion of A and similarly for C. 在javascript中,指令B的执行不依赖于A的完成,对于C也是类似的。

You may want to try something like: 您可能想尝试类似的方法:

var test = 0;
var i=0;
while(test!=1) {
  console.log(i);
  i++;
  if(i==1000) {
    alert("Hi!");
    test=1;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM