简体   繁体   English

为什么for(;;)永远不会终止?

[英]Why does for(;;) never terminate?

I always wondered why for(;;) acts like a while(true) . 我一直想知道为什么for(;;)表现得像while(true) For loops run as long as the condition in the middle is true. 只要中间条件为真,For循环就会运行。 It looks like here the condition is '' , 0 chars long. 看起来这里的条件是'' ,0个字符长。 Boolean('') clearly evaluates to false. Boolean('')显然为false。 So why does this run at all? 那么,为什么要这样运行呢?

See the docs : 文档

 for ([initialization]; [condition]; [final-expression]) 

Where condition is: condition是:

An expression to be evaluated before each loop iteration. 在每次循环迭代之前要计算的表达式。 If this expression evaluates to true, statement is executed. 如果此表达式的值为true,则执行语句。 This conditional test is optional. 此条件测试是可选的。 If omitted, the condition always evaluates to true. 如果省略,则条件始终为true。 If the expression evaluates to false, execution skips to the first expression following the for construct. 如果该表达式的计算结果为false,则执行将跳至for构造之后的第一个表达式。

Note that 注意

Boolean('')

is passing an empty string to Boolean , which is not the same as what's being done in the for condition (where there's nothing at all in the condition ). 正在通过一个空字符串 Boolean ,这是不一样什么在被做了同样for情况(这里有在什么在所有的 condition )。

If there does exist anything at all in condition (such as the empty string), then it's coerced to a Boolean . 如果确实存在任何condition (例如空字符串),则将其强制为Boolean For example, '' evaluates to false , so no iterations run: 例如, ''计算结果为false ,因此不会运行任何迭代:

 for (; '';) { console.log('iteration'); } console.log('done'); 

Really interesting question! 真有趣的问题! If we take a look at the docs , it appears that all 3 possible arguments, initialization, condition, and final expression, are optional. 如果我们看一下docs ,似乎所有3个可能的参数(初始化,条件和最终表达式)都是可选的。

for ([initialization]; [condition]; [final-expression]) {...}

Initialization doesn't really matter if it's omitted, as it's just there for convenience to declare a locally-scoped variable. 初始化是否被忽略并不重要,因为它只是为了方便地声明局部作用域变量。

Omitting the final expression also doesn't matter much, as it's just there for convenience, to do things like increment your counter variable and whatnot. 省略最终表达式也无济于事,因为它只是为了方便起见,可以执行诸如增加计数器变量之类的操作。

Interestingly, however, if the condition is omitted, the condition always evaluates to true. 然而有趣的是,如果省略的条件 ,条件计算结果始终为true。 This is somewhat counter-intuitive, in my opinion! 我认为这有点违反直觉!

So the key is the omission of condition. 因此,关键是条件的遗漏。 sunglasses 墨镜

That means the loop conditional check always evaluates to true, so it will keep looping forever unless someone puts a stop to the madness. 这意味着循环条件检查始终评估为true,因此它将一直循环下去,除非有人阻止了这种疯狂。

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

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