简体   繁体   English

node.js 中的空 for 循环行为

[英]Empty for loop behavior in node.js

I am trying to test for loop behavior in node.js.我正在尝试在 node.js 中测试循环行为。 In Javascript/node.js for loop is synchronous but what if their is no statement in the loop.在 Javascript/node.js 中 for 循环是同步的,但如果循环中没有语句怎么办。

For Example:例如:

 console.log("START") for(var i=0; i<100000000;i++){ } console.log("END")

When i run above code in node.js it just prints:当我在 node.js 中运行上面的代码时,它只打印:

START
END

And the execution completes.并且执行完成。

But if there is a statement in the loop, it executes complete loop and then ends:但是如果循环中有语句,则执行完整的循环然后结束:

 console.log("START") for(var i=0; i<100000000;i++){ console.log("LOOP "+i); } console.log("END")

The output is:输出是:

START
LOOP 0
LOOP 1
....
....
....
LOOP 99999999
END

So what happens if there is no statement in the for loop in node.js ?那么如果node.jsfor循环中没有语句会发生什么?

Even if there's no statement, yes, there are still some calculation like initialization , condition , and/or final-expression .即使没有语句,是的,仍然有一些计算,如初始化条件和/或最终表达式

Besides, sometimes people do use for without a statement.此外,有时人们确实会在没有声明的情况下使用 for。 You can take a look at MDN: Using for without a statement .你可以看看MDN: Using for without a statement

Finally i got it.最后我明白了。 For loop is always synchronous whether it is JavaScript or Node.js.无论是 JavaScript 还是 Node.js,for 循环总是同步的。 And node.js does not skip an empty loop.并且 node.js 不会跳过空循环。

Executed below code:执行以下代码:

console.log("START")
for(var i=0; i<10000000000;i++){
}
console.log(i);
console.log("END")

The output is:输出是:

START
10000000000
END

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

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