mardi 5 septembre 2017

Whats wrong with this JavaScript if/else statement?

So I'm learning JavaScript and I'm just playing around - bear with me here, I'm trying to learn some concepts so I'm hacking together a simple "Magic 8 ball" game. I thought if I used math.random I could generate a random number and use an if/else statement to show an "answer" based on the random number generated behind the scenes. The idea is for the user to never see the random number of course. My issue though is...no matter what I do, the script always shows the very first if/else answer though. What am I doing wrong?

Here is a link to my codepen example for reference: http://ift.tt/2gF2Rgl

var answer = prompt("What is your question?");
var number = Math.floor(Math.random() * 20) + 1;
var realAnswer = number;


if(realAnswer = 20) {
    document.write("It is certain");
} else if (realAnswer = 19) {
    document.write("It is decidedly so");
} else if (realAnswer = 18) {
    document.write("Without a doubt");
} else if (realAnswer = 17) {
    document.write("Yes definitely");
} else if (realAnswer = 16) {
    document.write("You may rely on it");
} else if (realAnswer = 15) {
    document.write("As I see it, yes");
} else if (realAnswer =14) {
    document.write("Most likely");
} else if (realAnswer = 13) {
    document.write("Outlook good");
} else if (realAnswer =12) {
    document.write("Yes");
} else if (realAnswer = 11) {
    document.write("Signs point to yes");
} else if (realAnswer = 10) {
    document.write("Reply hazy try again");
} else if (realAnswer = 9) {
    document.write("Ask again later");
} else if (realAnswer = 8) {
    document.write("Better not tell you now");
} else if (realAnswer = 7) {
    document.write("Cannot predict now");
} else if (realAnswer = 6) {
    document.write("Concentrate and ask again");
} else if (realAnswer = 5) {
    document.write("Don't count on it");
} else if (realAnswer = 4) {
    document.write("My reply is no");
} else if (realAnswer = 3) {
    document.write("My sources say no");
} else if (realAnswer = 2) {
    document.write("Outlook not so good");
} else {
    document.write("Very doubtful");
}
<div id="demo"></div>

Also, a side question, the above is also how I calculate a random number between 1 and 20?

Aucun commentaire:

Enregistrer un commentaire