到底是什么让第二个参数返回 true
?
WARNING: it will loop infinitely and might crash your browser
for(;;){
//...
}
我完全没想到会循环...
但它正在运行,这让情况变得更糟,因为它只能在评估为 true
的情况下运行,或者我是否遗漏了什么?
最佳答案
来自 for
MDN
for ([initialization]; [condition]; [final-expression])
statement
[Initialization]
和 [final-expression]
直觉上不是必需的,将构造简化为简单的 while
循环。但相关部分是:
condition
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.
(强调我的)
这似乎是一个完全任意的 JS 语言设计决定。如果是我的语言,我可能会抛出语法错误。
有趣的是,for(;;){}
等同于 while(true){}
,恰好短了 4 个字符。我想知道缩小器是否利用了这一点!
关于javascript - 为什么这个 'for(;;)' 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9936578/