简体   繁体   中英

Output Random Value From Array

I have the following javascript code:

  let gemStones = [
  "Amethyst",
  "Diamond",
  "Emerald",
  "Ruby",
  "Sapphire",
  "Topaz",
  "Onyx",
];

let randomGemStone = gemStones[Math.floor(Math.random()*gemStones.length)];

function findGems()
{
  console.log("You found a " + randomGemStone + "!");
}

Here's the html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="css.css">
  <title>1. Gem Pond</title>
</head>
<body>
  <h1>Gem Pond</h1>
  <script src="main.js"></script>
  <button id="gemPond_btn" onclick="findGems()">GET GEM</button>
</body>
</html>

When I click the "GET GEM" button several times in a row, I always get the same result instead of getting a random one.

I'm not sure what I'm doing wrong here.

Thanks in advance.

Move the let randomGemStone line into the findGems function:


function findGems()
{
  let randomGemStone = gemStones[Math.floor(Math.random()*gemStones.length)];
  console.log("You found a " + randomGemStone + "!");
}

Otherwise you run it only once on page load and not every time you click the button.

 let gemStones = [
  "Amethyst",
  "Diamond",
  "Emerald",
  "Ruby",
  "Sapphire",
  "Topaz",
  "Onyx",
];


const findGems = () => {
  let randomGemStone = gemStones[Math.floor(Math.random()*gemStones.length)];
  console.log(`You found a ${randomGemStone}!`);
}

Note I have moved randomGemStone inside the function. Or the value will only be updated once when the script loads, this way it will be random everytime findGems() is called

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