有什么办法可以减少这段代码吗?

时间:2014-12-22 08:23:27

标签: javascript switch-statement case reduce

我想在不创建功能的情况下减少代码。那么,有人有解决方案吗?

这是代码:

var level = {
                level1 : 3,
                level2 : {
                    win: 3,
                    draw : 2
                },
                level3 : 3,
                level4 : 3,
                level5 : 3,
                level6 : 3
            };          
            switch(levelIndex) {
                case 0:
                    if (winScore >= level.level1) {
                        levelIndex++;
                        this.resetGame();
                        game.state.start('rockpaperscissor');
                    } else {
                        game.state.start('gameover');
                    }
                break;
                case 1:
                    if (winScore >= level.level2.win && drawScore >= level.level2.draw) {
                        levelIndex++;
                        this.resetGame();
                        game.state.start('rockpaperscissor');                       
                    }
                    else {
                        game.state.start('gameover');
                    }
                break;
                case 2:
                    if (winScore >= level.level3) {
                        levelIndex++;
                        this.resetGame();
                        game.state.start('rockpaperscissor');           
                    }
                    else {
                        game.state.start('gameover');
                    }
                break;
                case 3:
                    if (winScore >= level.level4) {
                        levelIndex++;
                        this.resetGame();
                        game.state.start('rockpaperscissor');                       
                    }
                    else {
                        game.state.start('gameover');
                    }
                break;
             }
}

2 个答案:

答案 0 :(得分:0)

由于要执行的代码对于所有switch...case...if条件完全相同,您可以将它们合并为一个if ||(逻辑OR):

if (levelIndex == 0 && winScore >= level.level1 ||
    levelIndex == 1 && winScore >= level.level2.win && drawScore >= level.level2.draw ||
    levelIndex == 2 && winScore >= level.level3 ||
    levelIndex == 3 && winScore >= level.level4) {
    levelIndex++;
    this.resetGame();
    game.state.start('rockpaperscissor');
} else {
    game.state.start('gameover');
}

答案 1 :(得分:0)

避免测试,但我认为它应该有效

var lvl = 0; // Whatever level you're testing
if (winScore >= level['level'+lvl] || (level['level'+lvl].win <= winScore && level['level'+lvl].draw <= drawScore)) {
  levelIndex++;
  this.resetGame();
  game.state.start('rockpaperscissor');
} else {
  game.state.start('gameover');
}

应该修复。