[英]How can I convert this if, else if statement to switch-statement?
I'am new to javascript, just gaining the hang of it.我是 javascript 的新手,刚刚掌握了它的窍门。 This code i wrote for a rock, paper, scissors game works.
我为石头,纸,剪刀游戏作品编写的这段代码。 It changes color of the picked options, for the user and computer and if it's is a draw, changes it to black.
它会为用户和计算机更改所选选项的颜色,如果是平局,则将其更改为黑色。 Just curious to know if it needs refactoring ?
只是想知道它是否需要重构? And how to convert it to a switch-statement?
以及如何将其转换为 switch 语句?
I just cant get the hang of using switch statement with two arguments like this.我只是无法掌握使用带有两个参数的 switch 语句的窍门。
switch(userChoice, computerChoice){
case userChoice === computerChoice //or 'r' === 'r' :
//code block
break;
}
Doesn't seem to work.似乎不起作用。
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)
}
} }
Works well, just curious about refactoring and switch-statement.效果很好,只是对重构和 switch 语句感到好奇。
Usually you should use a switch-case statement for more than 2 cases, but anyway, have a look here:通常你应该对 2 个以上的情况使用 switch-case 语句,但无论如何,看看这里:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.