AlexT Posted December 5, 2014 Share Posted December 5, 2014 Hello Everyone,I have to change the if statements to a switch statement, in this game. Can anyone help? Thanks. var checkKeyPressed = function (e) { // Press key A or key D to make dog run to the left or right // The running speed is specified by the step variable, 10 by default. // If you replace 10 with a larger integer, the dog will run faster. //press A, dog runs left if (e.keyCode == "65") { if (prex[0] > 5) { prex[0] = prex[0] - step; } } //press D, dog runs right if (e.keyCode == "68") { if (prex[0] < right) { prex[0] = prex[0] + step; } } }; Quote Link to comment https://forums.phpfreaks.com/topic/292919-if-statement-to-switch-statement/ Share on other sites More sharing options...
Ch0cu3r Posted December 5, 2014 Share Posted December 5, 2014 Have you tried this your self? If you are not familiar with a switch then see here first Basically you pass e.keyCode as the expression. 65 and 68 will be used as the case expression. The if statements will go in the corresponding case statement. Quote Link to comment https://forums.phpfreaks.com/topic/292919-if-statement-to-switch-statement/#findComment-1498668 Share on other sites More sharing options...
AlexT Posted December 6, 2014 Author Share Posted December 6, 2014 Thanks for the link. How is this looking? switch (e.keyCode) { case '65': if (prex[0] > 5) { prex[0] = prex[0] - step; } break; case '68': if (prex[0] < right) { prex[0] = prex[0] + step; } break; Quote Link to comment https://forums.phpfreaks.com/topic/292919-if-statement-to-switch-statement/#findComment-1498706 Share on other sites More sharing options...
Alex_ Posted December 6, 2014 Share Posted December 6, 2014 That's the idea behind a switch statement. Should be no issues with that code you just wrote. However, because I'm picky, I want to point out that you are currently referencing your switch statement's keys with Strings. IE '65', '68'. Because browsers parse/react differently to javascript objects and keys/values, I'd like to make this suggestion: var keyCode = parseInt(e.keyCode); switch(keyCode) { case 65: ... break; case 68: ... break; } This way you can be sure it will work cross-browsers. I know some browsers tend to consider the keyCode as an integer, which makes sense. While others consider it a string. So in short, parsing the String to an Integer is the safer option here. Quote Link to comment https://forums.phpfreaks.com/topic/292919-if-statement-to-switch-statement/#findComment-1498756 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.