【问题标题】:Ternary Operator in JavaScript With Multiple Expressions?带有多个表达式的 JavaScript 中的三元运算符?
【发布时间】:2011-03-11 05:38:21
【问题描述】:
the_styles ? the_styles.appendTo('head'); the_styles=null : the_styles = $('.stylesheet').detach();

显然,这是无效的。注意“;”在appendTo()the_styles=null 之间。我如何将它写在 1 行并且仍然有多个这样的表达式?

【问题讨论】:

  • 提个建议:其他一些语言中的三元运算符不用于写完整的语句,而只用于表达式部分(即'='符号右侧的部分)。在 Java 中,这首先无法编译。最好不要养成这种习惯。

标签: javascript jquery conditional ternary-operator


【解决方案1】:

这样使用逗号运算符:

the_styles ? (the_styles.appendTo('head'), the_styles=null) : the_styles =  $('.stylesheet').detach();

以下是 Mozilla 开发者中心对逗号运算符的描述:

当您想在需要单个表达式的位置包含多个表达式时,可以使用逗号运算符。该运算符最常见的用法是在 for 循环中提供多个参数。

在此处阅读更多信息:https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator

【讨论】:

  • 这是一个非常简洁的表格。我也没想到大括号会如此深刻地改变语句的含义。我不认为我会偶然写这个,但比较var x = 1,y=2,z=3;var x = (1,y=2,z=3);。在第一种情况下,x 设置为 1。在第二种情况下,x 设置为 3。这真的,真的很整洁。
【解决方案2】:

谁需要三元运算符?

​the_styles = !the_styles && $('.stylesheet').detach()​​​​ ||
             the_styles.appendTo('head') && null;​

必须切换表达式,否则第一个表达式的 null 值将始终强制计算第二个表达式 .detach()

关于聪明的代码的唯一一点是,一旦你在喝咖啡休息后回到它,它甚至对你来说都没有任何意义。所以这要好得多:

if(the_styles) {
    the_styles.appendTo('head')
    the_styles = null;
}
else {
    the_styles = the_styles.detach('.stylesheet');
}

对我来说,即使是上述简单化的版本也没有任何意义。 what 部分很明显,但为什么要这样做?

【讨论】:

  • +1 - 我有类似的答案,但误读了意图。你是对的。
  • @patrick - 我花了一段时间来评估短路,这总是一个尖叫的信号,不要试图变得聪明:)
【解决方案3】:
the_styles=the_styles || $('.stylesheet').detach(); the_styles.appendTo('head');

【讨论】:

    【解决方案4】:
    the_styles ? the_styles.appendTo('head') : the_styles = $('.stylesheet').detach();
    

    如果你覆盖它,你不需要将它清空!

    【讨论】:

    • 我需要 null,因为如果没有,它会在初始点击后保持相同的值,我需要一个“关闭/打开”功能。
    【解决方案5】:

    我同意光晕编码器,但如果你仍然想要它:

    the_styles ? function(){ the_styles.appendTo('head'); the_styles=null;}() : the_styles = $('.stylesheet').detach();
    

    【讨论】:

      【解决方案6】:
      the_styles ? (function() {the_styles.appendTo('head'); the_styles=null})() : <etc>
      

      只需将代码块包装在 (function() {})() 中即可。

      现在最难的部分是:为什么你想这样做?也许有更好的解决方案!

      【讨论】:

      • 是的,那很丑,没关系。我只是喜欢三元的,因为它们很干净而且只有一行。
      • 只要每个分支中的代码是一个“行”,它们就很好。否则...使用多行!
      猜你喜欢
      • 2017-04-17
      • 2010-12-21
      • 1970-01-01
      • 2011-09-09
      • 2014-09-15
      • 2016-04-06
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      相关资源
      最近更新 更多