javascript - 三元运算符对变量的赋值优先级

标签 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"

问题:当使用三元 运算符时,它是否计算右操作数的最右项?所以如果我输入逗号,那么它会采用最右边逗号的表达式。

如果我以某种方式调用此过程,它会评估最右边的第二个项 (Q2)。

是不是所有的false子句都赋值给了变量?如果是这样,为什么输出只有 stop.html 而没有包含 SorryYou are much too young!

最佳答案

我正在编写这个小代码块来演示现在的三元运算。

给定以下代码:

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

和(&&)场景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

和(&&)场景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

关于javascript - 三元运算符对变量的赋值优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34441827/

相关文章:

Python变量赋值题

c++ - 如何在 C++ 中的头文件之外定义赋值运算符?

javascript - Jest 测试中未定义正则表达式

javascript - 在文本中查找关键字

javascript - 未捕获的安全错误 : Failed to execute 'replaceState' on 'History' in Chrome

javascript - JSON/JavaScript - 通过传递索引和属性名称获取值

c++ - if-check 和内联条件之间是否存在编译器差异?

c++ - 模板元编程三元值未达到基本情况

php - 是否可以在 PHP 中为此语句创建一个三元运算符?

java - 为什么三元运算符意外地转换为整数?