javascript - Cant not get two if else statements to work? checking strings and numbers -


i run these 2 if else statement can not them work ? please help.

  1. if input sting fail go beginning , ask again.

    function table(){     var num = prompt("please enter number");     if (num <= 0 && typeof num != 'string') {         alert("invalid number or zero") ;         table();     } else {         alert("ok") ;     } }  table(); 
  2. if not correct text beginning , ask again.

    function text(){     var txt = prompt("please enter rock or scissors or paper");     if (txt != "rock" || "scissors" || "paper") {         alert("failed") ;         table();     } else {         alert("ok") ;     } }  text(); 

thank you.

the typeof result prompt always either "string" (the user clicked ok or pressed enter) or "object" (the user clicked cancel or pressed esc), because typeof null "object" , prompt returns typed, or null on cancel. that's what's wrong first if.

if blanks not acceptable, simple check !:

var num = prompt(...); if (!num) {     // user clicked cancel or didn't type } 

...then use +num convert num number, or use parseint(num, 10) if want ensure base 10 , ignore text after number (parseint("42foo", 10) 42 rather nan; +"42foo" nan).

the second if's problem have repeat you're testing , use && rather ||:

if (txt != "rock" && txt != "scissors" && txt != "paper"){ 

"if txt not rock , txt not scissors and..."

a switch might useful there:

switch (txt) {     case "rock":     case "scissors":     case "paper":         alert("ok") ;         break;     default:         alert("failed") ;         table();         break; } 

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -