简体   繁体   中英

need help on while loop Javascript

first time on here. I'm trying to complete an application project regarding the while loop. I will paste the question in this and can anyone who has JavaScript knowledge give me a helping hand.

I've only just started out JavaScript probably about a month and a bit ago and struggle to remember everything. I've done a couple of while loops but until this question came up, it completed blanked my mind.

Here is the question;

Next,

create another HTML page with a block in the section of the document. This script should include the following:

Create a function named whileTest(). Inside the function, create a variable named number and assign it a value between 1 and 10.

Create another variable named answer and assign it a value of 0 (zero). Then create a while loop. Create code that will cause the loop to execute as long as the number variable does not equal the answer variable.

Inside the loop, assign the answer variable the return value from a prompt dialog box.

The prompt will ask the user to guess a number between 1 and 10. The loop will continue until the proper answer is entered.

After the loop exits, use an alert dialog box to inform the user of a correct guess.

Once you have the code working properly, create code that will allow the user only three guesses. If, after three guesses, the user has not entered the correct answer, exit the function and alert the user that he or she is out of guesses via an alert dialog box.

Ensure that only one dialog box appears after the function is exited, one with a correct guess message, or one asking the user to try again.

Experiment with different methods that you have seen for calling the function. You can use the load event or the onclick event handler of a form button.

Here I made you a startup, you can develop it to a full guessing game, happy coding:)

 function playAgainCheck() { if(confirm("Do you want to play Again?")) { whileTest(); } } function whileTest() { var n = Math.floor(Math.random() * 10) + 1, guess, i = 1; do { guess = prompt("Guess a number between 1 and 10 (both included)"); if(guess == n) { alert("You won;"); playAgainCheck(); break: } if(i++ === 3) { alert("Out of guesses;\nThe number was; " + n); playAgainCheck(); break; } } while(true); } whileTest();

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