带有coffescript语法的JavaScript-if条件:优化if语句结构

带有coffescript语法的JavaScript-if条件:优化if语句结构,javascript,function,if-statement,coffeescript,Javascript,Function,If Statement,Coffeescript,我有一个函数,正在测试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 >

我有一个函数,正在测试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

不确定优化是什么意思,但简而言之可能是:

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

起初,我使用了三元语法,但CoffeeScript不支持这种语法。供参考

编辑2:


@user633183建议使用
布尔值
,但我认为这会给出相同的结果。

您可以删除
真/假
,并对其进行如下优化:

$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;
};

你到底想优化什么?看起来还不错。
return($scope.postParams.options.scopes.report.from |$scope.postParams.options.scopes.report.to |$scope.postParams.options.template|id |$scope.displayOptions.query.length>0)
hi@timgwp,谢谢你的评论,这个结构看起来不错吧?还有比这更好的语法吗?你想破坏吗?如果我错了,请纠正我,但这不是JS的有效语法
$scope.filterActivated=->
。如果这是一个箭头函数,则必须有
=()=>
用于无参数删除
?true:false
和它做同样的事情-更好的
->Boolean(a | | | b | | | c | | d)
。。。那么,true else false
是相同的反模式。只要删除它。如果您想强制它返回布尔值,您可以将整个表达式包装在
!!(…)
@user633183我很好奇,你能指出一个引用,它说它是反模式的。@thinkxl
如果(条件)然后返回true,否则返回false
返回布尔值(条件)
–或
返回是一样的!!(条件)
如Barmar建议