我'新的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语句。
通常你应该使用switch-case语句超过2例,但无论如何,在这里看看:
const a = 1
const b = 2
const c = 1
function useSwitch(a,b) {
switch (a) {
case b:
console.log("first case")
break
case 1:
case 5:
console.log("second / third case")
break
}
}
useSwitch(a,b)
useSwitch(a,c)
useSwitch(5,b)
console.log("======")
function useIfElse(a, b) {
if (a === b) console.log("first case")
else if (a === 1 || a === 5) console.log("second / first case")
}
useIfElse(a,b)
useIfElse(a,c)
useIfElse(5,b)