为变量分配随机值

问题描述 投票:1回答:2

我对代码很新,所以我可能不理解一些答案。在此代码中,我无法将变量转换为1到10之间的随机数。

<script type="text/javascript">
var money = 0

function Random() {
  money = Math.floor((Math.random() * 10) + 1);
}
</script>

我已经读过我需要把return放在随后的随机代码中,但我只是不明白我把它放在何处使用它。

javascript function variables random
2个回答
2
投票

function Random() {
  return Math.floor((Math.random() * 10) + 1);
}

function getRandom() {
  var money = Random();
  console.log(money);
  document.getElementById("demo").innerHTML = money;
}
<button onclick="getRandom()">Click for random number</button>

<p id="demo"></p>

0
投票

这条线将起作用:

var money = Math.floor((Math.random() * 10) + 1);

但是如果你想使用一个函数,你可以写它:

var money;

function Random() {
  return Math.floor((Math.random() * 10) + 1);
}

// Re-usable anytime you want
money = Random();
© www.soinside.com 2019 - 2024. All rights reserved.