我是Java语言的新手,正在这些三元运算符上进行各种杂草工作。我有这个小的代码段:
const x = MSys.inShip ? 'ship launch' : '';
if (x != '') {send_command(x);}
虽然这足够有效,但是我很好奇它是否可以在函数调用中重写。类似于以下内容:
send_command(const x = MSys.inShip
? 'ship launch'
: MSys.alert("You aren't in your ship!);
这在当前示例中可能没有意义,但这是我当时的最佳想法。基本上,我喜欢三元样式的简写形式,以简化if / then条件语句的使用,但我不喜欢将其与必须随后调用的变量绑定的方式。我正在寻找一种无需使用变量即可使用该速记的方法。
最后,此操作的目的是查看您是否在船上,如果正在,请下水。如果您根本不执行任何操作,或者只是发送警报消息。
我很好奇它是否可以在函数调用中重写。
是的,可以。但是,如果您在那里进行操作,则不需要变量。您将直接内联传递函数的参数。
已经说过,您不能将MSys.alert()
语句作为“ else”值传递,因为它将在所有情况下执行。您必须在此处传递一个值,该函数可以将其用作输入参数
send_command(MSys.inShip ? 'ship launch' : 'some other string');
这里是一个例子:
function foo(x){
console.log(x);
}
// If a random number is even, pass "even". If not, pass "odd"
foo(Math.floor(Math.random() * 10) % 2 === 0 ? "even" : "odd");
两种方法之间的重要区别-第二种方法将始终调用send_command(),而第一种方法将有条件地调用它。
此区别将取决于您对send_command的实现而定,但是听起来您想要第一种方法的行为。
此外,您不能在函数调用中使用const声明变量。如果仅传递三元运算符,则最终将使用您的字符串或未定义的调用send_command(返回alert()的返回)。
但是,作为对您的问题的回答,是的,您可以将三元运算符传递给函数,就像其他任何值一样。三元运算符是一个将返回值的表达式。
从技术上讲,您可以在下面保留一个变量(例如operation
),该变量引用您要执行的方法,具体取决于某些条件。然后,您可以将该变量方法传递给它应该获得的可变字符串。
所以,正如您所看到的,它[[可以完成。但是,请查看添加了多少复杂性的过程,而不仅仅是使用简单的if else语句。
function test_logic ( inShip ) {
// if they are in their ship, the operation should be the send_command method
// otherwise it should be the window alert
var operation = inShip ? send_command : window.alert;
function send_command ( command ) {
console.log( command );
}
// give the operation the desired string
operation( inShip ? 'ship launch' : "You aren't in your ship!" );
}
console.log( "Not in ship test" );
test_logic( false );
console.log( "In ship test" );
test_logic( true );