javascript - The value of the ternary arithmetic expression 3<8?(9<6?7:5):2>0?4:1 is different in Java and PHP. What is the solution?
三叔
三叔 2017-06-08 11:02:07
0
6
1061


The evaluation result in java and js is 5, but in PHP it is 4
Is it because my formula is not written in a standard way? Or is it for other reasons? I asked others to try it using .net and c language, and all the results were 5
[Solved] Thank you for your answers. My guess is that the formula is not very standardized, because I always feel that The ternary is from right to left, so I omitted the last bracket (I often wrote it this way before). I will correct it. For the sake of standardization, it should be 3<8?(9<6?7:5):(2>0 ?4:1)

三叔
三叔

reply all(6)
typecho

The problem with the combination direction of the ternary operator:
java from right to left. Equivalent to 3<8?(9<6?7:5):(2>0?4:1)
php from do to right. Equivalent to (3<8?(9<6?7:5):2)>0?4:1

Therefore, in order to avoid the generation of ambiguous code, it is better not to omit the parentheses that should be written

过去多啦不再A梦

PHP’s ternary operation combination order is reverse
http://www.jianshu.com/p/124f...

代言

I guess PHP interprets priorities differently from Java, JS and other languages. It may be interpreted as (3 < 8 ? (9 < 6 ? 7 : 5) : 2 > 0) ? 4 : 1

某草草

In PHP it looks like this:

$a = (3 < 8 ? (9 < 6 ? 7 : 5): 2 > 0)
    ? 4
    : 1;

So it’s 4;

In JavaScript it looks like this:

var a = (3 < 8)
    ? (9 < 6 ? 7 : 5)
    : (2 > 0 ? 4 : 1);

So it’s 5.

So if you don’t know the precedence of the operator, just complete the brackets. ^_^

刘奇

Correct answer upstairs~~~~~~

学霸

Shouldn’t I type this photo?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template