JavaScript: 是否允许在 `if` 语句中使用 `ternary` 语句?
JavaScript: Is it allowed to use a `ternary` statement inside an `if` statement?
在下面的脚本中,我在 if
语句的 else if
部分使用了 ternary
语句,将两者并列。在这种情况下,我是否应该在 else if
中替换另一个 if
语句?
var attackOpt = prompt('Which attack option does Angelo use in this turn?');
// Remaining number of times Angelo can cast spells:
var angMP = 3;
// Validity Check to see if the attack option entered can be executed:
while (true) {
if (attackOpt === 'slash') {
break;
}
else if (attackOpt === 'magic') {
(angMP) ?
break;
: attackOpt = prompt('Angelo can no longer cast spells. Select again.');
}
}
不需要它会正常工作没有任何问题
(angMP) ? break : attackOpt = prompt('Angelo can no longer cast spells. Select again.');
是的,它会起作用,但会使代码难以阅读。考虑修改您的 'while' 循环:
while (attackOpt !== 'slash' && angMP) {
attackOpt = prompt('Angelo can no longer cast spells. Select again.');
}
当然,这是一种风格选择,完全取决于您。
是的,您可以在任何允许表达式的地方使用三元运算符表达式(它不是语句)。
但是 三元运算符使用表达式作为它的 3 个参数。 break
不是表达式,而是语句。你不能在那里使用 break
。
您必须使用 if
语句。
你不能这样做。会导致语法错误,代码不会运行。三元运算符用于在没有 if-else 的情况下快速 return 值。不允许休息。但是,您可以在一行中使用类似的东西:
if (angMP) break; else attackOpt = prompt('Angelo can no longer cast spells. Select again.');
或者代码其他部分的更简单形式:
if (angMP) break;
在下面的脚本中,我在 if
语句的 else if
部分使用了 ternary
语句,将两者并列。在这种情况下,我是否应该在 else if
中替换另一个 if
语句?
var attackOpt = prompt('Which attack option does Angelo use in this turn?');
// Remaining number of times Angelo can cast spells:
var angMP = 3;
// Validity Check to see if the attack option entered can be executed:
while (true) {
if (attackOpt === 'slash') {
break;
}
else if (attackOpt === 'magic') {
(angMP) ?
break;
: attackOpt = prompt('Angelo can no longer cast spells. Select again.');
}
}
不需要它会正常工作没有任何问题
(angMP) ? break : attackOpt = prompt('Angelo can no longer cast spells. Select again.');
是的,它会起作用,但会使代码难以阅读。考虑修改您的 'while' 循环:
while (attackOpt !== 'slash' && angMP) {
attackOpt = prompt('Angelo can no longer cast spells. Select again.');
}
当然,这是一种风格选择,完全取决于您。
是的,您可以在任何允许表达式的地方使用三元运算符表达式(它不是语句)。
但是 三元运算符使用表达式作为它的 3 个参数。 break
不是表达式,而是语句。你不能在那里使用 break
。
您必须使用 if
语句。
你不能这样做。会导致语法错误,代码不会运行。三元运算符用于在没有 if-else 的情况下快速 return 值。不允许休息。但是,您可以在一行中使用类似的东西:
if (angMP) break; else attackOpt = prompt('Angelo can no longer cast spells. Select again.');
或者代码其他部分的更简单形式:
if (angMP) break;