【发布时间】:2019-07-04 05:46:42
【问题描述】:
我是 javascript 的新手,刚刚掌握了它的窍门。我为石头、纸、剪刀游戏编写的这段代码有效。它为用户和计算机更改所选选项的颜色,如果是平局,则将其更改为黑色。只是想知道它是否需要重构?以及如何将其转换为 switch 语句?
我只是无法掌握使用带有这样两个参数的 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)
}
}
效果很好,只是对重构和 switch 语句感到好奇。
【问题讨论】:
-
因此您已经知道要将其转换为什么,但您需要展示您在尝试转换时所做的努力。 * 不是免费的代码编写或重构服务。此处的目标是在代码无法按预期工作或卡住时帮助修复代码
标签: javascript switch-statement refactoring