从数组输出随机值



我有以下javascript代码:

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 + "!");
}

这是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>

当我点击";获取GEM";按钮,我总是得到相同的结果,而不是随机得到的结果。

我不确定我在这里做错了什么。

提前谢谢。

let randomGemStone移动到findGems函数中:


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

否则,在页面加载时只运行一次,而不是每次单击按钮时都运行。

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}!`);
}

注意,我已经在函数中移动了randomGemStone。或者,当脚本加载时,该值只会更新一次,这样,每次findGems((被调用时,它都是随机的

最新更新