我在这里的游戏是一个猜谜游戏,它计算猜谜次数,并且不包含任何重复的猜想。
我正在尝试将变量try从函数try传递给函数try,但是它将不起作用。计数保持为0,但是当我通过sameGuess.length时,它为什么起作用?
let random = Math.round(Math.random()*100);
let guess = false;
let sameGuess = []
let tries = sameGuess.length;
function game(){
while (guess === false){
let myGuess = prompt('Guess a number between 0-100:');
numCheck(myGuess);
if (myGuess == random){
guess = true;
repeats(myGuess, sameGuess);
attempts(tries, sameGuess);
}else if (myGuess < random){
repeats(myGuess, sameGuess);
alert('Your number was too small, try again!');
guess = false;
}else if (myGuess > random){
repeats(myGuess, sameGuess);
alert('Your answer was too big, try again!');
guess = false;
}
}
}
function attempts(tries, sameGuess){
if (sameGuess.length == 1){
alert('Well done, you got it frist try!');
document.write("<h1>GUESSING GAME</h1><p>Thank you for playing the Guessing Game <br> Created by Jonathan Fox</p>");
}else if (sameGuess.length <= 15){
alert('You took ' + sameGuess.length + ' tries');
alert('Well done, you didn\'t take too many tries!');
document.write("<h1>GUESSING GAME</h1><p>Thank you for playing the Guessing Game <br> Created by Jonathan Fox</p>");
}else if (sameGuess.length >=16){
alert('You took ' + sameGuess.length + ' tries');
alert('You got it, but lets see less tries next time!');
document.write("<h1>GUESSING GAME</h1><p>Thank you for playing the Guessing Game <br> Created by Jonathan Fox</p>");
}
}
function repeats(myGuess, sameGuess){
if ((sameGuess.indexOf(myGuess)) == -1){
(sameGuess.push(myGuess));
}else alert('You have already guessed that number! - Dont worry, i haven\'t counted it!');
}
function numCheck(myGuess){
if (isNaN(myGuess)){
alert('Enter a number, don\'t try and be sneaky!');
}
}
game ();
答案 0 :(得分:0)
当您访问array.length
时,该值将被复制 ,这意味着即使您将一个值添加到数组中,该值也不会更新:
var array = [];
var length = array.length;
console.log(length); // 0
array.push('Some value');
console.log(length); // Still 0, since it was copied, it is _not_ a reference to the live value
console.log(array.length); // 1, this is a live reference to the length of the array
就目前而言,您的代码可以正常工作,尽管您可以像现在一样删除它的tries
方面并直接使用sameGuess.length
。
有关Pass by Reference or Pass by Value的更多讨论,请参见此帖子。
答案 1 :(得分:0)
您应该尝试输入= sameGuess.length;一会儿!