【问题标题】:JavaScript with coffescript syntax- if condition : optimize if statement structureJavaScript 与 coffescript 语法 - if 条件:优化 if 语句结构
【发布时间】:2019-03-10 03:01:09
【问题描述】:

我有一个函数,我正在测试 4 个变量,我想优化我的 if 语句测试的结构,有人可以帮忙吗? :

$scope.filterActivated = ->
    if $scope.postParams.options.scopes.report.from || $scope.postParams.options.scopes.report.to || $scope.postParams.options.template_id || $scope.displayOptions.query.length > 0
      return true
    else
      return false

【问题讨论】:

  • 您到底想优化什么?看起来一点也不差。
  • return ($scope.postParams.options.scopes.report.from || $scope.postParams.options.scopes.report.to || $scope.postParams.options.template_id || $scope.displayOptions.query.length > 0)
  • 嗨@Timggwp,感谢您的评论,这个结构看起来不错?还有其他语法看起来比这更好吗?
  • 你在寻找破坏吗??
  • 如果我错了,请纠正我,但这不是 JS $scope.filterActivated = -> 的有效语法。如果这是一个箭头函数,则必须有 = () => 用于无参数

标签: javascript function if-statement coffeescript


【解决方案1】:

不确定您所说的优化是什么意思,但可以简写为:

$scope.filterActivated = ->
    $scope.postParams.options.scopes.report.from
    || $scope.postParams.options.scopes.report.to
    || $scope.postParams.options.template_id
    || $scope.displayOptions.query.length;

编辑:

最初,我使用三元语法,但 CoffeeScript 不支持。供参考Ternary operation in CoffeeScript

编辑 2:

减少了一点,@user633183 建议使用Boolean,但我认为这给出了相同的结果。

【讨论】:

  • 删除 ? true : false 和它做同样的事情 - 更好 -> Boolean (a || b || c || d)
  • ... then true else false 是相同的反模式。删除它。
  • 如果你想强制它返回一个布尔值,你可以将整个表达式包裹在!!(...)中。
  • @user633183 你能指出它说是反模式的参考吗,我很好奇。
  • @thinkxl if (condition) then return true else falsereturn Boolean (condition)return !!(condition) 相同,正如 Barmar 建议的那样
【解决方案2】:

您可以删除true/false 并像这样优化它:

$scope.filterActivated = ->
  options = $scope.postParams.options
  options.scopes.report.from or options.scopes.report.to or options.template_id or $scope.displayOptions.query.length > 0

编辑:JS 给你:

$scope.filterActivated = () => {
  let options = $scope.postParams.options;
  return options.scopes.report.from || options.scopes.report.to || options.template_id || $scope.displayOptions.query.length > 0;
};

【讨论】:

    猜你喜欢
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多