简体   繁体   中英

Trying to generate numbers with eventListener

I want generate random lottery numbers, ranging from 1-59 with 7 numbers showing. They have to generate on the click of a submit button. Im struggling to get it to write to the console log saying random is not defined.

let lottoNum = [];
while (lottoNum.length < 7) {
  let random = Math.floor(Math.random() * 59) + 1;
  if (lottoNum.indexOf(random) === -1) lottoNum.push(random);
}

let btn = document.getElementById("Button");
button.addEventListener("click", function getNumbers() {
  return random;
});

random is not defined

You was close, you should research into scopes however. Try the following:

generateNumbers = () => {
  let lottoNum = [];
  while (lottoNum.length < 7) {
    let random = Math.floor(Math.random() * 59) + 1;
    if (lottoNum.indexOf(random) === -1) lottoNum.push(random);
  }
  return lottoNum;
}

let btn = document.getElementById("Button");
btn.addEventListener("click", function getNumbers() {
  const nums =  generateNumbers();
  console.log(nums);
});

I've put your main code into a function and returned it from said function. From there i've called the function in your click listener and logged them. You can do anything you'd like where i've done console.log however.

The reason you had your "random is not defined" is because you do let random inside your while loop. That means anything that isn't inside of the {} of your while loop cannot read random. hence the function and return :)

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