【问题标题】:javascript question mark ?: logical syntax, defensive programmingjavascript问号?:逻辑语法,防御性编程
【发布时间】:2013-11-07 02:18:17
【问题描述】:

我正在尝试使用 javascript ?: 语法重写下面的语句。

if(type of someVariable !="undefined"){
     someFunction(someVariable);
}else{}

这是我目前的尝试,导致语法错误

typeof someVariable != "undefined" ? someFunction(someVariable) : ;

如果有人能告诉我我做错了什么,我将不胜感激。欢迎提供任何有关防御性编程最佳实践的随附提示。

【问题讨论】:

    标签: javascript function variables if-statement defensive-programming


    【解决方案1】:

    ?: 样式(需要: 两侧的表达式):

    typeof(someVariable) != 'undefined' ? someFunction : null;
    

    忍者风格:

    someVariable !== undefined && someFunction(someVariable);
    

    [编辑:我不能发誓 noop 是 Javascript 中的一个东西,但显然我错了。切换到null]

    【讨论】:

    • jQuery.noop 是个东西
    【解决方案2】:

    尽管三元运算控制了程序流程,但我只会在赋值运算或从函数返回值时使用它。

    检查一下: Benefits of using the conditional ?: (ternary) operator

    【讨论】:

      【解决方案3】:

      它应该看起来像这样。

      someVariable != undefined ? someFunction(someVariable):someOtherfunction(someOtherVarialbe);
      

      如果你不想要 else 语句并且想要它在单行中,你可以这样做:

        if(someVariable != undefined){someFunction(someVariable);}
      

      【讨论】:

      • typeof 不是函数。您不需要在它之后使用()。它返回一个字符串,因此您需要与"undefined" 进行比较。但最好只做someVariable != undefined
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多