简体   繁体   English

使用 ? 时的无限循环:“for”循环内的条件

[英]Infinite loop while using ?: condition inside "for" loop

These are the two examples to compare the difference:这是比较差异的两个示例:

 for (var i = 0; i < 1 < 2 ? 1 : 2; i++) { console.log(i); }

It will log:它会记录:

1 2 3 ... 1000 2000 3000 ... 1 2 3 ... 1000 2000 3000 ...

 for (var i = 0; i < (1 < 2 ? 1 : 2); i++) { console.log(i); }

It will log:它会记录:

0 0

My question: What is the difference between我的问题:有什么区别

i < 1 < 2 ? 1 : 2

and

i < (1 < 2 ? 1 : 2)

P/S: If you're using Chrome to view this question, please pressing Shift + Esc to open Chrome Task Manager to force to stop running the script in this page (If it doesn't stop after clicking Run code snippet ). P/S:如果您使用 Chrome 查看此问题,请按Shift + Esc打开 Chrome 任务管理器以强制停止运行此页面中的脚本(如果单击Run code snippet后没有停止)。

Thank you!谢谢!

The answer is in JavaScript's operator precedence .答案就在JavaScript 的运算符优先级中 Per that list, the < operator is higher precedence than the ?: conditional operator, and < has left-to-right associativity, so i < 1 < 2 ? 1 : 2根据该列表, <运算符的优先级高于?:条件运算符,并且<具有从左到右的结合性,因此i < 1 < 2 ? 1 : 2 i < 1 < 2 ? 1 : 2 is interpreted as ((i < 1) < 2) ? 1 : 2 i < 1 < 2 ? 1 : 2被解释为((i < 1) < 2) ? 1 : 2 ((i < 1) < 2) ? 1 : 2 . ((i < 1) < 2) ? 1 : 2

Immediately, you can see that it doesn't matter what the < conditions resolve to;立即,您可以看到<条件解析为什么并不重要; the only possible results are 1 and 2 , both of which are "truthy".唯一可能的结果是12 ,它们都是“真实的”。

For completeness, i < 1 produces true for i==0 , and false for i>0 , which when used in numeric context, has a value of 1 or 0 respectively, but since both 1 < 2 and 0 < 2 both reliably produce true , the whole expression is always evaluating to 1 .为了完整性, i < 1i==0产生true ,为i>0产生false ,当在数字上下文中使用时,其值分别为10 ,但由于1 < 20 < 2都可靠地产生true ,整个表达式的计算结果始终为1

Your first loop is being evaluated as this:您的第一个循环正在评估如下:

 for (var i = 0; (i < 1) < 2 ? 1 : 2; i++) { console.log(i); if (i > 100) break; // added to stop the infinite loop }

The expression (i < 1) will be true , or 1 , when i=0 .i=0时,表达式(i < 1)将为true1 For values of i >= 0 , the expression (i < 1) will be false, which will be implicitly converted to 0 .对于i >= 0值,表达式(i < 1)将为 false,它将被隐式转换为0 For all values of i , the inequality (i < 1) < 2 will evaluate to true, so the value 1 will be the output of the ternary expression.对于i所有值,不等式(i < 1) < 2将评估为真,因此值1将是三元表达式的输出。 Actually, it doesn't even matter whether (i < 1) < 2 is true or false, because the outcomes are 1 and 2, both of which are truthy.实际上, (i < 1) < 2是真还是假都没有关系,因为结果是 1 和 2,两者都是真。 So, your loop is basically equivalent to the following:所以,你的循环基本上等同于以下内容:

for (var i = 0; true; i++) {
    console.log(i);
}

That is, it just boils down to an infinite loop in i .也就是说,它只是归结为i的无限循环。

In the demo above, I added a break statement to the loop to prevent it from crashing your browser.在上面的演示中,我在循环中添加了一个break语句,以防止它使您的浏览器崩溃。

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

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