JavaScript 与 coffescript 语法 - if 条件:优化 if 语句结构



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

你可以删除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;
};

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

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

编辑:

最初,我使用了三元语法,但 CoffeeScript 不支持。供参考 CoffeeScript 中的三元运算

编辑 2:

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

最新更新