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
而没有包含 Sorry
或 You 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/