每次在Javascript中调用函数时,都会生成一个新的随机数

时间:2020-01-12 21:49:12

标签: javascript function

我正在尝试学习JavaScript,我正在玩一个随机选择游戏。

我想拥有2个函数,随机和猜测。随机会在1-10之间产生一个新数字。猜猜是检查数字是否被猜到的地方,如果没有,则重新运行随机函数并生成一个新的数字进行尝试。

var x;
function random(){
    let x = Math.floor((Math.random() * 10) + 1);
    guess();
 }

function guess(x){
    if(x === 3){
        alert('you are correct!');
    }else{
        alert('try again');
        random();
    }
}

random();

这只是提醒每次尝试重试一次,我想是因为每次调用该函数时都不会生成新的数字吗?

如何创建随机函数,使其在每次调用时都会生成一个新数字?

*****更正,它似乎会生成一个新数字,但是x在猜测函数中未定义**

4 个答案:

答案 0 :(得分:3)

x中的guess()是作为参数传递给它的x。我会在调用var x;

时删除guess(x)声明并传递一个值
function random(){
    const x = Math.floor((Math.random() * 10) + 1);
    guess(x);
 }

function guess(x){
    if(x === 3){
        alert('you are correct!');
    }else{
        alert('try again');
        random();
    }
}

random();

答案 1 :(得分:2)

guess函数的签名表明它接受了一个参数x,但是在调用该函数时,您没有将任何值传递给该函数,因此它将undefined分配给{{1 }}在运行x时将永远不会等于guess。您可以采取2种方法来解决此问题。首先,您可以通过取消在3函数中定义x的{​​{1}}并删除{{来使let成为全局变量x的函数签名中的1}},如下所示:

random

或者,您可以通过删除x全局声明并将guess传递给var x; function random() { x = Math.floor((Math.random() * 10) + 1); guess(); } function guess() { if (x === 3) { alert(x + '- you are correct!'); } else { alert(x + '- try again'); random(); } } random();来将x用作猜测函数的参数var x;函数中,如下所示:

x

我个人甚至没有guess功能。我只是在random中定义function random() { let x = Math.floor((Math.random() * 10) + 1); guess(x); } function guess(x) { if (x === 3) { alert(x + '- you are correct!'); } else { alert(x + '- try again'); random(); } } random();并从其内部调用random。而且,我将使用randojs.com使随机性更具可读性。这是我的处理方式:

x
guess

请注意,guess语句将立即停止该函数的执行,因此,如果正确猜中该数字,它将不会进入“重试”警报。

答案 2 :(得分:1)

我对您的代码进行了一些更改。 您对函数调用函数的概念有疑问。 在实际代码中,它将杀死您的内存。.您的函数调用函数未关闭,然后一次又一次调用该函数,并填充了内存。

var x;
// flag correct will close the loop when you have right umber 
var correct = false;
function random() {
    x = Math.floor((Math.random() * 10) + 1);
    guess(x);
}

function guess(x) {
    if (x === 3) {
        alert('you are correct!');
        // if number is right flag is up 
        correct = true;
    } else {
        alert('the number is ' + x + ' try again');
    }
}
// loop until the number is right
while (correct != true) {
    random();
}

答案 3 :(得分:1)

这里有一些详细的代码,可以帮助您了解如何在浏览器中运行这样的游戏。

请参阅评论以了解其工作原理(并在MDN上搜索信息以了解有关任何特定主题的更多信息。)

祝您编程愉快!

def parseData(urls):
    f = io.open('output.txt', 'a', encoding='utf-8')
    for url in urls:
        response = urllib.request.urlopen(url)
        responseContent = response.read()
        pageSoup = BeautifulSoup(responseContent, 'html.parser', from_encoding="utf-8")
        if 'https://example.com' in url:
            name = pageSoup.findAll('h3', {'class': 'tb-main-title'})[0].string
            price = pageSoup.findAll('em', {'class': 'tb-rmb-num'})[0].string
            link = url
            print('Retriving data from ' + str(link) + '...\n' + str(name) + ':' + str(price))
            f.write('\n' + str(link) + '\n' + str(name) + '\n' + str(price) + '\n')

        elif 'https://example2.com' in url:
            name2 = pageSoup.findAll('div', {'class': 'item-title'})[0].string
            price2 = pageSoup.findAll('span', {'class': 'cur-price'})[0].string
            print('Retriving data from ' + str(link) + '...\n' + str(name2) + ':' + str(price2))
            f.write('\n' + str(link) + '\n' + str(name2) + '\n' + str(price2) + '\n')
// Identifies HTML elements
const
  guessInput = document.getElementById("guessInput"),
  outputParagraph = document.getElementById("outputParagraph");

// Makes a global variable that all functions can access
let globalNum;

// Invokes the main function
playGame();


function playGame(){
  
  // Invokes the randomizer function and stores the result in the global variable
  globalNum = getRandomNumber();
  //console.log(globalNum);
  
  // Invokes the output function
  setOutput("Guess a number from 1 to 10");

  // Assigns a function that will be invoked whenever the user changes the input field
  guessInput.addEventListener("change", respondToGuess);  

  // Puts the focus in the input element
  guessInput.focus();
}


// Defines a listener function that can automatically see the triggering event
function respondToGuess(event){

  // Gets the `target` element of the event and stores it in a local variable
  const localReferenceToInputElement = event.target

  // The text of an `<input>` element lives in its "value" property
  const inputText = localReferenceToInputElement.value;

  // Tries to convert the text string to an integer (and store it locally as 'guess')
  let guess = parseInt(inputText);

  // If the conversion failed, changes the output accordingly
  if(!guess){ setOutput("Please enter a valid number"); }

  // If the number is out of range, changes the output
  else if(guess < 1 || guess > 10){ setOutput("Only numbers from 1 to 10 are allowed"); }

  // If the guess doesn't match the stored number, changes the output
  else if(guess !== globalNum){ setOutput("Try again..."); }

  // If we got this far, the guess was correct, so changes output and ends game
  else{
    setOutput("You guessed it!");
    reset();
  }
}


function getRandomNumber(){
  // Returns a random number into whatever function called this function
  const x = Math.floor((Math.random() * 10) + 1);
  return x;
}

function setOutput(outputText){
  // The text of a paragraph element lives in its `innerHTML` property
  outputParagraph.innerHTML = outputText;  
}

function reset(){
  // Clears the input and stops listening for changes
  guessInput.value = "";
  guessInput.removeEventListener("change", respondToGuess);
}