【问题标题】:Shorthand if ? return : null速记 if ?返回:空
【发布时间】:2014-07-16 11:16:00
【问题描述】:

我想实现这个:

 if (full) {
      return
    }
    else{
      // nuthin
    }

但更短,例如:

full ? return : null;

但这不起作用..

我能做到:

if (full) { return }

但我更喜欢三元

我希望像 full ? return 这样的东西可以工作......

我基本上是想在值为真的时候跳出当前函数... 有没有更好的/有效的速记可用?

【问题讨论】:

    标签: javascript refactoring ternary-operator shorthand shorthand-if


    【解决方案1】:

    三元的参数是表达式 不是 语句

    return; 是一个声明,因此您的提议在语法上无效。

    您的if 声明尽可能简洁:尤其是如果您删除了不必要的大括号。

    【讨论】:

      【解决方案2】:

      所以这是尽可能短的:

       if full return
      

      【讨论】:

        【解决方案3】:

        说明

        如果您只想测试是否为真,您可以使用逻辑与运算符&&,如下所示:

        index.js:

        (function(){
            var full=true;
            full&&alert('Glass is full');
        })();
        

        请注意,在此示例中,var full=false; 不会发生任何事情。

        源代码

        JSFiddle source-code.

        Codepen source-code

        Pastebin source-files

        【讨论】:

          猜你喜欢
          • 2014-06-14
          • 2013-08-30
          • 1970-01-01
          • 2011-12-26
          • 1970-01-01
          • 1970-01-01
          • 2014-11-15
          • 2012-09-12
          • 2013-07-18
          相关资源
          最近更新 更多