【问题标题】:Using ternary operators in a function with javascript在带有 javascript 的函数中使用三元运算符
【发布时间】:2019-07-15 22:58:36
【问题描述】:

我是 Javascript 的新手,并且正在研究这些三元运算符的杂草。我有这个小代码段:

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 条件的三元样式的简写,但我不喜欢它如何与必须调用的变量相关联。我正在寻找一种无需绑定变量即可使用该速记的方法。

最后,这样做的目的是查看您是否在船上,如果在,则启动。如果您什么都不做,或者只是发送警报消息。

【问题讨论】:

  • 如果不希望在x为空的情况下调用该方法,那么不,将三元放在方法调用参数中是没有意义的。
  • if (Msys.inShip) send_command('ship launch');
  • 对,我只是想看看是否有可能,因为 javascript 中的 if/then 对所有括号都感到麻木。感谢您的帮助。
  • 之后还需要x吗?

标签: javascript ternary-operator


【解决方案1】:

我很好奇它是否可以在函数调用内部重写。

是的,可以。但是,如果你在那里做,那么就不需要变量。您将直接内联传递函数的参数。

话虽如此,您不能将 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");

【讨论】:

  • 这是我试图找到的,谢谢!我知道有更简单的方法可以写出我上面的内容,但我只是在探索可以在熟悉该语言的同时移动 javascript 的不同方式。非常感谢!
【解决方案2】:

您的两种方法之间的一个重要区别 - 第二种方法将始终调用 send_command() 而您的第一种方法将有条件地调用它。

这种区别取决于您对 send_command 的实现,但听起来您想要第一种方法的行为。

此外,您不能在函数调用中使用 const 声明变量。如果您只是传入三元运算符,您最终将使用您的字符串或未定义(调用 alert() 的返回)调用 send_command。

但是,作为对您问题的回答,是的,您可以像任何其他值一样将三元运算符传递给函数。三元运算符是一个会返回值的表达式。

【讨论】:

    【解决方案3】:

    从技术上讲,您可以在下面保留一个变量(例如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 );

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-19
      • 2020-08-02
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 2020-05-21
      相关资源
      最近更新 更多