如何将if,else if语句转换为switch语句?

时间:2019-02-10 16:38:22

标签: javascript switch-statement refactoring

我是javascript新手,刚掌握了它。我为岩石,纸张,剪刀游戏作品编写的代码。对于用户和计算机,它会更改所选选项的颜色,如果是平局,则将其更改为黑色。只是好奇地知道是否需要重构?以及如何将其转换为开关状态?

我只是无法使用带有两个这样的参数的switch语句。

switch(userChoice, computerChoice){
case userChoice === computerChoice //or 'r' === 'r' :
 //code block
break;
} 

似乎没有用。

function changeColor (userChoice, computerChoice) {

// If it's a draw, change color to black circle

if (userChoice === computerChoice) {
    document.getElementById(userChoice).classList.add('draw-pick');
    setTimeout( () => {
        document.getElementById(userChoice).classList.remove('draw-pick');
    }, 1000)

// If not a draw, change user pick to green and computer pick to red

} else if (userChoice === 'r' || 's' || 'p' && computerChoice === 'r' || 's' || 'p' ) {
    document.getElementById(userChoice).classList.add('user-pick');
    setTimeout( () => {
        document.getElementById(userChoice).classList.remove('user-pick');
    }, 1000)
    document.getElementById(computerChoice).classList.add('comp-pick');
    setTimeout( () => {
        document.getElementById(computerChoice).classList.remove('comp-pick');
    }, 1000)
}   

}

效果很好,只是对重构和转换语句感到好奇。

1 个答案:

答案 0 :(得分:0)

通常,对于两种以上的情况,您应该使用switch-case语句,但是无论如何,请在此处查看:

import tkinter
win = tkinter.Tk()
Checkbutton1 = Checkbutton(win,highlightthickness=0,bd=0).pack()
win.mainloop()