Javascript:"if" 条件内的三元运算符
Javascript: ternary operator inside "if" condition
我找到了这段 Javacript 代码,但我无法理解在 if 条件中使用三元运算符意味着什么。
var s = 10, r = 0, c = 1, h = 1, o = 1;
if (s > r ? (c = 5, h = 2) : h = 1, o >= h)
{
alert(1);
}
o >= h
返回的结果是否在 "if" 条件下进行评估?
那么在 "if" 条件下使用逗号呢?
这实际上只是一种语法捷径。可以将其扩展为两个 if
语句:
var condition;
if (s > r) {
c = 5;
condition = (h = 2); // another short-cut; it's essentially (h = 2, condition = true)
}
else {
h = 1;
condition = (o >= h);
}
if (condition) {
alert(1);
}
使用 comma
允许将两个语句变成一个语句(因为 a, b
总是计算为 b
,尽管 a
和 b
sub -表达式在过程中被评估)。
当你 运行 时这段代码不会给出错误...基本上...所做的是 运行 它找到 (c=5,h=2) 的三元运算不是写if语句的条件..
因此条件不会满足并且不会警报(1);
我找到了这段 Javacript 代码,但我无法理解在 if 条件中使用三元运算符意味着什么。
var s = 10, r = 0, c = 1, h = 1, o = 1;
if (s > r ? (c = 5, h = 2) : h = 1, o >= h)
{
alert(1);
}
o >= h
返回的结果是否在 "if" 条件下进行评估?
那么在 "if" 条件下使用逗号呢?
这实际上只是一种语法捷径。可以将其扩展为两个 if
语句:
var condition;
if (s > r) {
c = 5;
condition = (h = 2); // another short-cut; it's essentially (h = 2, condition = true)
}
else {
h = 1;
condition = (o >= h);
}
if (condition) {
alert(1);
}
使用 comma
允许将两个语句变成一个语句(因为 a, b
总是计算为 b
,尽管 a
和 b
sub -表达式在过程中被评估)。
当你 运行 时这段代码不会给出错误...基本上...所做的是 运行 它找到 (c=5,h=2) 的三元运算不是写if语句的条件..
因此条件不会满足并且不会警报(1);