我想重复代码,直到用户获得no。对。我该怎么做呢 ? 这是代码: -
function getRandomNumber(min,max){
return Math.floor(Math.random()*(max - min + 1 ))+min;
}
randomNumber=(getRandomNumber(1,10));
input=prompt("Please enter a no. between 1 and 10:","");
if(input==randomNumber){
console.log("Good Work");
}else{
console.log("not matched");
}
答案 0 :(得分:0)
您可以使用while循环调用" break"用户输入正确答案后的语句,或者您可以使用如下函数:
function getInput(){
input=prompt("Please enter a no. between 1 and 10:","");
if(input==randomNumber){
console.log("Good Work");
}else{
consol.log("not matched");
getInput(); //Gets the user's input again
}
}
答案 1 :(得分:0)
你去......
在开始之前需要将Found设置为false,否则该函数将只运行一个。在while循环中有函数定义没什么意义,因为它将被创建为全局变量。
var found = false;
function getRandomNumber(min,max) { return Math.floor(Math.random()*(max - min + 1 ))+min; }
while ( found != true ) {
var randomNumber = getRandomNumber(1,10);
console.log('Random Number is..',randomNumber);
var input = prompt("Please enter a no. between 1 and 10:","");
if ( input == randomNumber ) {
alert('Well Done')
found = true;
} else {
console.log("not matched");
}
}