变量的三元运算符分配优先级
Posted
技术标签:
【中文标题】变量的三元运算符分配优先级【英文标题】:Ternary Operator Assignment Precedence to Variable 【发布时间】:2016-03-30 06:02:06 【问题描述】: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)。
是否所有的假子句都分配给了变量?如果是这样,为什么输出只有stop.html
,不包括Sorry
或You are much too young!
?
【问题讨论】:
问:你为什么要把时间浪费在这么反常的事情上?对于“真实代码”,您想尝试避免不确定的行为,不是吗?建议:1) 用“Console.log()”替换“alert()”,2) 在调试器下单步调试代码,3) 一定要尝试几种不同的浏览器。例如,Chrome 的行为是否与 FF/Firebug 不同? IE11 和 IE8 有什么不同? 您的代码对我来说运行良好。确保您启用了弹出窗口。 这仅仅是因为所有的语句都被执行了,但只有最后一个返回被分配了。如果您使用||
运算符而不是,
,那么它将在第一个值处停止。但是,是的,这似乎是三元运算符的错误用例。
【参考方案1】:
我正在编写这个小代码块来演示现在的三元工作。
给定下面的代码:
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
【讨论】:
以上是关于变量的三元运算符分配优先级的主要内容,如果未能解决你的问题,请参考以下文章