Javascript 随机数生成器出现 NaN

标签 javascript nan

我正在尝试使用表单制作随机数生成器。当您按下按钮并输入最大数字时,它会出现一个显示 NaN 的对话框,此时它意味着会产生随机数。

我有一些代码,如下所示:

<html>
<head>

</head>
<body>

<form name="gen">

<h1>Random Number Generator</h1>

<b>Number:</b> 1 to
<input id="numgen" type="text"/>               

<button name="generate" type="submit" onclick="gennum()">Generate!</button>

<script>
function gennum()
{
alert(Math.floor(Math.random() * num.value + 1));
}

var num = document.getElementById('numgen').value;
</script>

</form>

</body>
</html>

我不太擅长Javascript,但我知道一点。如果有人知道如何解决这个问题,我会很高兴。

最佳答案

num.value 是一个字符串。使用 parseInt(num.value, 10) 将其转换为数字,这样就可以适本地与数字相加。

此外,您似乎获得了该值两次,第一次是在页面加载时(因此它还没有值:

var numElem = document.getElementById('numgen'); //remove value here

然后在你的函数中:

alert(Math.floor(Math.random() * parseInt(num.value + 1)));

并且,您需要在按钮上使用 type="button",否则页面将重新加载。

这是使用更好的实践重构的代码。

Live demo here (click).

标记:

<form name="gen">
  <h1>Random Number Generator</h1>

  <b>Number:</b> 1 to
  <input id="numgen" type="text"/>               

  <button id="generate" type="button">Generate</button>
</form>

JavaScript:

/* get element references */
var genButton = document.getElementById('generate');

var numInput = document.getElementById('numgen');

//use javascript to add the click function
genButton.addEventListener('click', function() {
  /* it's easier to read and debug if you break things up
   * instead of putting it all on one line with tons of ((()))
   */
  var rand = genRandom(1, parseInt(numInput.value, 10));
  alert(rand);
});

function genRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

关于Javascript 随机数生成器出现 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20456918/

相关文章:

javascript - 使用React Native Onauth而不是函数对Firebase中的用户进行身份验证

javascript - 如何在 Firebug 中调试脚本?

c - 在 C 编程中,如果表达式中的任何变量是 nan,计算会变慢吗

java - Java 中对 NaN 的困惑

javascript - `isNaN(' blabla');` -> 是怎么回事,一个误报?

java - MSSQL 中浮点字段中的 NaN 值

python - 删除数据帧中集合中的 'NaN' 值

javascript - 未捕获的类型错误 : Cannot read property 'addClass' of undefined in jquery slider

javascript - Backspace 删除整个 span 元素

javascript - 在指定时间临时更改 HTML 中的占位符