They're a lot of ways to parse numbers. Here's a few more:
parseFloat(b); // Also parses decimals: '5.3' -> 5.3
parseInt(b, 10); // Gives an integer (base 10): '5.3' -> 5
+b; // A very 'short' way; '5.4' -> 5.4
Number('5.4e2'); // Number case: '5.4e2' -> 540
Now to repeat? Make it a loop!
var a = 432;while (true) {var b = prompt("Enter a number in between 1 and 1000");if (b == a){alert("You're right!");break; // Stops loop} else if (!b) { break; } else {alert("Incorrect! Try again!");}}
Not sure why, but some people hate while true
loops. They shouldn't cause any problems as long as you coded it properly
You can get a random number using Math.random
.
var min = 1,max = 1000;Math.floor(Math.random() * (max - min + 1)) + min;
If you're like me and want short code, you can shorten it by:
Math.floor(Math.random() * (999)) + 1;
var a = Math.floor(Math.random() * (999)) + 1;while (true) {var b = prompt("Enter a number in between 1 and 1000");if (b == a) {alert("You're right!");break; // Stops loop} else if (!b) {alert("The Correct Answer was: " + a); //Shows correct answerbreak;} else {alert("Incorrect! Try again!");}}
Just stick your prompt in some kind of loop. The code will inside the loop will run over and over until the comparison is false
.
Basic example:
http://jsfiddle.net/s2he1twj/
var a = 500,b;while (parseInt(b) !== a) {b = prompt('Enter a number!');if (b === null) break;}
while
loopDo this recursively by calling the same function like
var a = 489;function promptGuess(){//var b stores whatever value the user enters.var b = prompt("Enter a number in between 1 and 1000");// if/else statement that test if the variables are equal.if (b == a){alert("You're right!");} else {alert("Incorrect! Try again!");promptGuess();}}promptGuess();
Use a while until the match:
var a = 489; var b;while(b != a) {var b = prompt("Enter a number in between 1 and 1000");if (b == a) {alert("You're right!");} else {alert("Incorrect! Try again!");}}
One more thing: although the b != a evaluation is correct, it's error-prone. The != operator do conversion type, whilst the !== operator compares types and value.
In your case: 5 != '5' will return false, but 5 !== '5' returns true. It's recommended that your comparisons be conversion-free. It's more strict.
In your case, this means:
while(parseInt(b) !== a)
Greetings!