作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我一直通过阅读书籍和练习所学知识来自学和练习 JavaScript。我对如何让某些东西发挥作用有点困惑,希望你们能提供帮助。
function guessAge(){
var userInput = parseInt(prompt("Guess my age!", 100),10);
if(userInput == 25){
alert("Correct!");
}else{
alert("Incorrect");
}
return guessAge();
}
function guessMovie(){
var input = prompt("Guess my favourite movie!");
if(input == "Lego"){
alert("Everything is awesome!");
}else{
alert("Incorrect!");
}
}
guessAge(); //Initialise guessAge function
guessMovie(); //Initialise guessMovie function
如果答案错误,我想让第一个函数重复,但如果答案正确,则继续执行下一个函数,但无论正确还是错误,return 似乎都会重复。
最佳答案
Rubber duck debugging是发现逻辑错误的好方法。注释中的内容是您在逐行执行代码时对橡皮鸭大声说的话。
function guessAge() {
/*
I'm asking the user for input with a default value of 100
I'm then parsing a string to an integer that is base 10
I store the result in userInput
*/
var userInput = parseInt(prompt("Guess my age!", 100), 10);
/*I check if the user input is 25 */
if (userInput == 25) {
/* The user input is 25 so I alert that they are correct */
alert("Correct!");
} else {
/* otherwise I alert that they are incorrect */
alert("Incorrect");
}
/*I return what guessAge returns. Right now there is no other
return statements out of the function so I will always call
this line */
return guessAge();
}
第一次通过后再次进行,但这次说出你想做什么。
function guessAge() {
/*
I want the user input to see if they can guess my age
*/
var userInput = parseInt(prompt("Guess my age!", 100), 10);
/*I check if the user input is 25 */
if (userInput == 25) {
/* The user input is 25 so I alert that they are correct */
alert("Correct!");
/* I want to leave the function guessAge after the user guesses
correctly. */
} else {
/* otherwise I alert that they are incorrect */
alert("Incorrect");
/* I want to call guessAge again since the user guessed wrong */
}
/* this statement is out of my control flow block so it will always
be reached, even if the user entered the correct age. I want to
leave the function when the user enters the correct answer but
this line will allways call guessAge */
return guessAge();
}
从那里您可以尝试一些解决方案。请记住,解决问题的方法有多种。
function guessAge() {
var userInput = parseInt(prompt("Guess my age!", 100), 10);
if (userInput == 25) {
alert("Correct!");
/* I want to leave the function guessAge after the user guesses
correctly. if I do nothing after my else we will leave the
function without having to do anything */
} else {
alert("Incorrect");
/* I want to call guessAge again since the user guessed wrong */
guessAge();
}
}
请注意,您不必从函数返回任何内容。调用函数时也不必总是返回。当您想要将值返回给函数调用者时,可以使用 return。
关于javascript - 如何从第一个功能转到下一个功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42227235/
我是一名优秀的程序员,十分优秀!