In the test I encountered the following situation:
var y=10; var z=3; var x=(y%5>0)?(z==3)? z*2 : y+3 :(z<3)? yz :z++; console.log(x); // 3 Prompt what sequence of calculations in such line. Thank!
In the test I encountered the following situation:
var y=10; var z=3; var x=(y%5>0)?(z==3)? z*2 : y+3 :(z<3)? yz :z++; console.log(x); // 3 Prompt what sequence of calculations in such line. Thank!
The colon is always the last question mark before it. The sequence of actions is as follows:
x= y%5>0 ? ( z==3 ? z*2 : y+3 ) : ( z<3 ? yz : z++ ) ; Here you can find a detailed analysis of the implementation of ternary operators in various programming languages, including javascript.
The order in js is simple and logical: first, the leftmost condition is checked. If it is true, the left part after the first colon is executed and returned, if not then the right part.
It should be separately clarified that the operators are executed from right to left .
In the example you cited, the implementation can be represented in approximately the following steps:
(y%5>0)?(z==3)? z*2 : y+3 :(z<3)? yz :z++; //исходный код false ? true ? z*2 : y+3 : false ? yz : z++ //выполнили скобки //теперь можно выделить три отдельных тернарных оператора: //(false ? (true ? z*2 : y+3) : (false ? yz : z++)) //выполняем их справа налево false ? true ? z*2 : y+3 : z++ false ? z*2 : z++ z++ //так как здесь постинкремент - получаем просто "3" Source: https://ru.stackoverflow.com/questions/562830/
All Articles
(y % 5 > 0) ? ( (z == 3) ? z * 2 : y + 3 ) : ( (z < 3) ? y - z : z++);(y % 5 > 0) ? ( (z == 3) ? z * 2 : y + 3 ) : ( (z < 3) ? y - z : z++);- Alexey Shimansky