javascript - (How) Can i use 'or' in a switch statement? -
is following code right:
var user = prompt("is programming awesome?").touppercase(); switch (user) { case 'hell yeah' || 'yes' || 'yeah' || 'yep' || 'yea': console.log("that's i'd expected!"); break; case 'kinda'||'cant say': console.log("oh, you'd when you'll pro!"); break; case 'hell no'||'no'||'nah'||'nope'||'na': console.log("you can't that!"); break; default: console.log("wacha tryna mate?"); break; }
i tried it. didn't work wanted to. worked if input 'hell no' or 'hell yeah', later strings ignored!
i approach using dictionary (object) containing answers can check function in switch statement. it's lot neater having multiple case checks:
var user = prompt("is programming awesome?").touppercase(); // 'hell yeah'; // 'dictionary' js object has key/value pairs // in instance have keys map case checks // making , each has corresponding array value, filled // or checks wanted make. // pass 'dict' in second parameter when call checkanswer var dict = { yes: ['hell yeah', 'yes', 'yeah', 'yep', 'yea'], maybe: ['kinda', 'cant say'], no: ['hell no', 'no', 'nah', 'nope', 'na'] }; // checkanswer returns 'yes' user prompt 'hell yeah' // loops on 'dict' object , if finds instance of // user input in 1 of arrays returns key // in instance 'yes' 'hell yeah' (indexof returns 0) // otherwise returns false (for 'default' case) function checkanswer(user, dict) { (var p in dict) { if (dict[p].indexof(user) > -1) return p; } return false; } // use checkanswer return key // user input found in 1 of dictionary arrays. // single string switch expects switch (checkanswer(user, dict)) { case 'yes': console.log("that's i'd expected!"); break; case 'maybe': console.log("oh, you'd when you'll pro!"); break; case 'no': console.log("you can't that!"); break; default: console.log("wacha tryna mate?"); break; }
Comments
Post a Comment