简体   繁体   中英

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 ...

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

It will log:

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 ).

Thank you!

The answer is in JavaScript's operator precedence . 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 is interpreted as ((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".

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 .

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 . For values of i >= 0 , the expression (i < 1) will be false, which will be implicitly converted to 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. 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. 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 .

In the demo above, I added a break statement to the loop to prevent it from crashing your browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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