I am trying to make a function that involves switch() and gives me answers on specific, randomly generated numbers. Somehow my function does not run the case it is supposed to run. It only gives me the default case, no matter what the number is.
This is my code:
var i;
var girl;
function response() {
var girl = prompt("What girl do you like?");
var r = (Math.random() * (3 - 1 + 1) + 1).toFixed(0);
var i = r;
switch(i) {
case (i == 1):
alert(girl + " likes you as a friend.");
break;
case (i == 2):
alert(girl + " does not really like you.");
break;
case (i == 3):
alert(girl + " has a crush on you.");
break;
case (i == 4):
alert(girl + " wants you to ask her out.");
break;
default:
console.log(i);
}
}
That's not how a switch works. It compares the value for each case
to the switch
.
Essentially now, it is comparing the value of i
multiple times to boolean values (the result of, for example i == 1
).
Also, your randomness doesn't become more random by adding arithmetic with static values into the value like you did. You should replace it with 4
. You also should use something like Math.ceil()
(since you're ignoring the 0
value, which is also probably not a good idea), not toFixed()
which returns a string.
You also don't need the parenthesis around the values to compare. If you know the range of the random number, you also probably don't need a default case (since you cover every possibility already).
You can also use r
directly, no need to reassign it.
Your variables are also local to your function, so probably don't need them at the top.
Here is how I would re-write this:
function response() {
var girl = prompt("What girl do you like?");
var r = Math.floor(Math.random() * 4);
switch(r) {
case 0:
alert(girl + " likes you as a friend.");
break;
case 1:
alert(girl + " does not really like you.");
break;
case 2:
alert(girl + " has a crush on you.");
break;
case 3:
alert(girl + " wants you to ask her out.");
break;
}
}
...or even...
function response() {
var answerSuffixes = [
" likes you as a friend.",
" does not really like you.",
" has a crush on you.",
" wants you to ask her out."
];
var girl = prompt("What girl do you like?");
var r = Math.floor(Math.random() * answerSuffixes.length);
alert(girl + answerSuffixes[r]);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments