|
| 1 | +The task demonstrates how postfix/prefix forms can lead to different results when used in comparisons. |
| 2 | + |
1 | 3 | <ol> |
2 | | -<li>**От 1 до 4** |
| 4 | +<li>**From 1 to 4** |
3 | 5 |
|
4 | 6 | ```js |
5 | 7 | //+ run |
6 | 8 | var i = 0; |
7 | 9 | while (++i < 5) alert( i ); |
8 | 10 | ``` |
9 | 11 |
|
10 | | -Первое значение: `i=1`, так как операция `++i` сначала увеличит `i`, а потом уже произойдёт сравнение и выполнение `alert`. |
| 12 | +The first value is `i=1`, because `++i` first increments `i` and then returns the new value. So the first comparison is `1 < 5` and the `alert` shows `1`. |
11 | 13 |
|
12 | | -Далее `2,3,4..` Значения выводятся одно за другим. Для каждого значения сначала происходит увеличение, а потом -- сравнение, так как `++` стоит перед переменной. |
| 14 | +Then follow `2,3,4…` -- the values show up one after another. The comparison always uses the incremented value, because `++` is before the variable. |
13 | 15 |
|
14 | | -При `i=4` произойдет увеличение `i` до `5`, а потом сравнение `while(5 < 5)` -- это неверно. Поэтому на этом цикл остановится, и значение `5` выведено не будет. |
| 16 | +Finally, `i=4` is incremented to `5`, the comparison `while(5 < 5)` fails and the loop stops. So `5` is not shown. |
15 | 17 | </li> |
16 | | -<li>**От 1 до 5** |
| 18 | +<li>**From 1 to 5** |
17 | 19 |
|
18 | 20 | ```js |
19 | 21 | //+ run |
20 | 22 | var i = 0; |
21 | 23 | while (i++ < 5) alert( i ); |
22 | 24 | ``` |
23 | 25 |
|
24 | | -Первое значение: `i=1`. Остановимся на нём подробнее. Оператор `i++` увеличивает `i`, возвращая старое значение, так что в сравнении `i++ < 5` будет участвовать старое `i=0`. |
| 26 | +The first value is again `i=1`. The postfix form of `i++` increments `i` and then returns the *old* value, so the comparison `i++ < 5` will use `i=0` (contrary to `++i < 5`). |
| 27 | + |
| 28 | +But the `alert` call is separate. It's another statement which executes after the increment and the comparison. So it gets the current `i=1`. |
25 | 29 |
|
26 | | -Но последующий вызов `alert` уже не относится к этому выражению, так что получит новый `i=1`. |
| 30 | +Then follow `2,3,4…` |
27 | 31 |
|
28 | | -Далее `2,3,4..` Для каждого значения сначала происходит сравнение, а потом -- увеличение, и затем срабатывание `alert`. |
| 32 | +Let's stop on `i=4`. The prefix form `++i` would increment it and use `5` in the comparison. But here we have the postfix form `i++`. So it increments `i` to `5`, but returns the old value. Hence the comparison is actually `while(4 < 5)` -- true, and the control goes on to `alert`. |
| 33 | + |
| 34 | +The value `i=5` is the last one, because on the next step `while(5 < 5)` is false. |
| 35 | +</li> |
| 36 | +</ol> |
29 | 37 |
|
30 | | -Окончание цикла: при `i=4` произойдет сравнение `while(4 < 5)` -- верно, после этого сработает `i++`, увеличив `i` до `5`, так что значение `5` будет выведено. Оно станет последним.</li> |
31 | | -</ol> |
|
0 commit comments