三元运算符和 OR 运算符的运算顺序

Order of Operations with ternary operator and OR operator

为什么第一个例子的运算顺序是从右到左?

计算结果为 World

"Hello" || true ? "World" : ""

计算结果为 Hello

"Hello" || (true ? "World" : "")

这是由于逻辑优先。

在第一个例子中,逻辑是用来判断输出的是"World"还是""。如果任一情况 "Hello" || true 为真,三元运算符将输出 "World".

在第二种情况下,如果短路评估失败,|| 用作回退。也就是说,如果第一个值为真,则尝试输出第一个值。如果第一个值,在本例中 "Hello" 为假,则计算下一个值 (true ? "World" : "").

在这两个示例中,逻辑在第一个值 (Hello) 上的计算结果为真。不同的是,第一种情况作为三元运算符作为使用

的快捷方式
if ("Hello" || true) {
    return "World"
} else {
    return ""
}

可能你知道操作不是从左到右执行的,而是遵循运算符的优先级:想想:

1 + 2 * 3

你期待7还是9?正如您所试验的,三元运算符的优先级较低。

"Hello" || true ? "World" : ""

相当于

("Hello" || true) ? "World" : ""

希望这对您有所帮助。

希望对你有所帮助。

"Hello" || true ? "World" : ""; 

//is the same as:

if("Hello" || true) {
 console.log("World")
} else {
 console.log("");   
};              // Outputs World


console.log("Hello" || (true ? "World" : "")); //Outputs Hello

//sentence after OR is like:

if(true) {
 "World";
} else {
 "";
}
    
//For example:

console.log((true ? "World" : "") || "Hello"); //Outputs World

console.log("Hello" || (true ? "World" : "")); //Outputs Hello