这就是我想出来帮助自己理解左vs.三元运算符的右结合。
// PHP
$a = "T";
$vehicle = $a == "B" ? "bus" :
$a == "A" ? "airplane" :
$a == "T" ? "train" :
$a == "C" ? "car" :
$a == "H" ? "horse" : "feet";
// (as seen by the PHP interpreter)
// INITIAL EXPRESSION: ((((($a == "B" ? "bus" : $a == "A") ? "airplane" : $a == "T") ? "train" : $a == "C") ? "car" : $a == "H") ? "horse" : "feet");
// STEP 1: (((((FALSE ? "bus" : FALSE) ? "airplane" : TRUE) ? "train" : FALSE) ? "car" : FALSE) ? "horse" : "feet")
// STEP 2: ((((FALSE ? "airplane" : TRUE) ? "train" : FALSE) ? "car" : FALSE) ? "horse" : "feet")
// STEP 3: (((TRUE ? "train" : FALSE) ? "car" : FALSE) ? "horse" : "feet")
// STEP 4: (("train" ? "car" : FALSE) ? "horse" : "feet")
// STEP 5: ("car" ? "horse" : "feet")
// FINAL EVALUATION: ("horse")
// If you used the initial expression here (with the parenthesis) in a different language, it would also evaluate to "horse."
echo $vehicle; // gives us "horse"
这是作为反对:
// EVERY OTHER LANGUAGE
var a = "T";
var vehicle = a == "B" ? "bus" :
a == "A" ? "airplane" :
a == "T" ? "train" :
a == "C" ? "car" :
a == "H" ? "horse" : "feet";
// (as seen by the other language's interpreter)
// INITIAL EXPRESSION: (a == "B" ? "bus" : (a == "A" ? "airplane" : (a == "T" ? "train" : (a == "C" ? "car" : (a == "H" ? "horse" : "feet")))));
// STEP 1: (FALSE ? "bus" : (FALSE ? "airplane" : (TRUE ? "train" : (FALSE ? "car" : (FALSE ? "horse" : "feet")))))
// STEP 2: (FALSE ? "bus" : (FALSE ? "airplane" : (TRUE ? "train" : (FALSE ? "car" : "feet"))))
// STEP 3: (FALSE ? "bus" : (FALSE ? "airplane" : (TRUE ? "train" : "feet")))
// STEP 4: (FALSE ? "bus" : (FALSE ? "airplane" : "train"))
// STEP 5: (FALSE ? "bus" : "train")
// FINAL EVALUATION: ("train")
// If you used the initial expression here (with the parenthesis) in PHP, it would also evaluate to "train."
console.log(vehicle); // gives us "train"
如果你注意到,在PHP例子中,最里面的表现是在左边,而在第二个例子中,最里面的表达式在右边。每个步骤都会评估下一个最内层的表达式,直到出现单个结果。如果您要在PHP中嵌套三元运算,括号显然非常重要!
添加关联隐含的括号,您将看到原因。 –
问题的直观表示:http://i.imgur.com/1zgFd.jpg – Almo