三元算子赋值变量的优先级

时间:2015-12-23 18:43:02

标签: javascript variable-assignment ternary-operator conditional-operator operator-precedence

var url = age > 18 ? (
    alert("OK, you can go."),
    // alert returns "undefined", but it will be ignored because
    // isn't the last comma-separated value of the parenthesis
    "continue.html" // the value to be assigned if age > 18
) : (
    alert("You are much too young!"),
    alert("Sorry :-("), // Q2) ***When does it evaluate this line?
    // etc. etc.
    "stop.html" // the value to be assigned if !(age > 18) Q1) this line is evaluated first right?
);
location.assign(url); // "stop.html"

问题:使用ternary运算符时,它是否评估了右操作数的最右项?所以,如果我加入逗号,那么它将采用最右边的逗号表达。

如果我以某种方式呼吁这个过程,它会评估第二个最右边的术语,(Q2)。

是否所有的false子句都分配给变量?如果是这样,为什么输出仅为stop.html且不包括SorryYou are much too young!

1 个答案:

答案 0 :(得分:2)

我正在编写这一小块代码来展示现在的三元作品。

鉴于以下代码:

function isGreater(a, b) {
    console.log('in isGreater');
    return a > b;
}

function isLess(a, b) {
    console.log('in isLess');
    return a < b;
}

function times2(v) {
    console.log('in times2');
    return v * 2;
}

function times3(v) {
    console.log('in times3');
    return v * 3;
}

或(||)场景1

// 1. isGreater is called and return true (since true so isLess is never called)
// 2. since true, only times2 is called
var x1 = isGreater(1, 0) || isLess(1, 0) ? times2(5) : times3(5);
console.log('x1 is ' + x1);

输出:

in isGreater
in times2
x1 is 10

或(||)场景2

// 1. isGreater is called, but return false
// 2. so isLess is called and return true
// 3. since true, only times2 is called
var x2 = isGreater(0, 1) || isLess(0, 1) ? times2(10) : times3(10);
console.log('x2 is ' + x2);

输出:

in isGreater
in isLess
in times2
x2 is 20

和(&amp;&amp;)场景1

// 1. isGreater is called and return true
// 2. because true, isLess is called and return true
// 3. since both are true, only times2 is called
var x3 = isGreater(1, 0) && isLess(0, 1) ? times2(20) : times3(20);
console.log('x3 is ' + x3);

输出:

in isGreater
in isLess
in times2
x3 is 40

和(&amp;&amp;)场景2

// 1. isGreater is called, but return false (since false, isLess is never called)
// 2. since false, only times3 is called
var x4 = isGreater(0, 1) && isLess(0, 1) ? times2(30) : times3(30);
console.log('x4 is ' + x4);

输出:

in isGreater
in times3
x4 is 90