简体   繁体   中英

Javascript if/else statements help, what am i doing wrong with this code?

The following code is from my course and I can't get it to work.

I've tried putting everything possible that i can think of

 var eatSteak = confirm("Do you eat steak?"); var confirmSteak = confirm("You like Steak!"); var confirmNoSteak = confirm("Here's a tofu stir-fry"); var howOld = prompt("How old are you?"); var howNotOld = confirm("No Sake for you!"); var sakeForYou = confirm("Sake for you!"); var tryAgain = confirm("TRY AGAIN!"); if (eatSteak == true) { alert(confirmSteak); } else { alert(confirmNoSteak); } if (howOld < 21) { alert(howNotOld); } else if (howOld >= 21) { alert(sakeForYou); } else { alert(tryAgain); } 

No error messages displayed by console

confirm() should only be used to ask a question. If you just want to set a variable to a message, you shouldn't call confirm() . So statements like

var confirmSteak = confirm("You like Steak!");

should just be

var confirmSteak = "You like Steak!";

Also, when you're testing howOld , you check if they're less than 21, then check if they're at least 21. Those are the only two possibilities, it can never get to the last else block. So you can just use if and else -- either they get sake or not.

 var eatSteak = confirm("Do you eat steak?"); var confirmSteak = "You like Steak!"; var confirmNoSteak = "Here's a tofu stir-fry"; var howOld = prompt("How old are you?"); var howNotOld = "No Sake for you!"; var sakeForYou = "Sake for you!"; if (eatSteak == true) { alert(confirmSteak); } else { alert(confirmNoSteak); } if (howOld < 21) { alert(howNotOld); } else { alert(sakeForYou); } 

One simple rule. Use prompt and confirm only when you want to get a user input.

 if (confirm("Do you eat steak?") == true) alert('You like Steak!') else alert('Heres a tofu stir-fry'); //Here is a variable which stores the user input var age = prompt("How old are you?"); if (age < 21) alert('No Sake for you!') else if (age > 21) alert('Sake for you!') else alert('TRY AGAIN!'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM