我如何优化long if if to优化版本

时间:2015-07-23 10:39:35

标签: javascript angularjs

在我的下面的代码中,我根据Anding操作设置了两个范围变量的状态。

取决于调用相关方法的键(两种方法的不同之处在于检查prop3。

我觉得它有相当简化的代码,但不确定我如何优化它。 知道如何用短代码实现我的目标吗?

if(key =='White')
    _checktests1();
else
    _checktests2 ();

var _checktests1 = function () {
    if ($scope.test.Prop1 == "one" && $scope.test.Prop2 == "two")
        $scope.checkWhiteStatus = true;
    else
        $scope.checkWhiteStatus = false;

    if ($scope.test.Prop1 == "three" && $scope.test.Prop2 == "four" )
        $scope.checkGreenStatus = true;
    else
        $scope.checkGreenStatus = false;
}
var _checktests2 = function () {
    if ($scope.test.Prop1 == "one" && $scope.test.Prop2 == "two" && $scope.test.Prop3 == "five")
        $scope.checkWhiteStatus = true;
    else
        $scope.checkWhiteStatus = false;

    if ($scope.test.Prop1 == "three" && $scope.test.Prop2 == "four" $scope.test.Prop6 == "six")
        $scope.checkGreenStatus = true;
    else
        $scope.checkGreenStatus = false;
}

1 个答案:

答案 0 :(得分:4)

你可以这样做:

$scope.checkWhiteStatus = ($scope.test.Prop1 == "one" && $scope.test.Prop2 == "two" && (key =='White' || $scope.test.Prop3 == "five"));

$scope.checkGreenStatus = ($scope.test.Prop1 == "three" && $scope.test.Prop2 == "four" && (key =='White' || $scope.test.Prop6 == "six"));