2016-01-18 44 views
-2

下面是一个函数,它应该在用户指定的两个数字之间产生一个随机数。如果我手动指定数字,该方程将起作用。但是,如果我使用提示功能,它似乎会产生一个完全随机的数字。为什么我不能在函数中使用使用prompt()创建的变量?

function randOm() { 
    var high = prompt("high"); 
    var low = prompt("low"); 
    return Math.floor(Math.random() * (high - low + 1)) + low; 
} 

document.write(randOm()); 
+3

提示()返回你一个字符串,所以你必须之前将其转换如果您使用的console.log使用它在数学运算 – leguano

+0

( )来揭示提示所收集的内容,它似乎是一个整数。为什么会这样?此外,为什么方程式不错误,并说NaN? –

回答

0

您将需要使用parseFloat将其转换为一个Number

0

转换提示的结果在数字,因为它返回的字符串:

return Math.floor(Math.random() * ((+high) - (+low) + 1)) + (+low); 
0

prompt被称为返回string,因此u必须convertstring to integer另一个缺点是,执行你的operations.And之前,如果用户在提示框中输入“hello”或“hi”等任何字符,您的函数可能会返回NaN,因为无法将字符分析为数字。

脚本:

function randOm() { 
 
    var high = prompt("high"); 
 
    var low = prompt("low"); 
 
    var h=parseInt(high); 
 
    var l=parseInt(low); 
 
    return Math.floor(Math.random() * (h - l + 1)) + l; 
 
} 
 

 
document.write(randOm());

0
if (Number.isNaN(high) || Number.isNaN(low)){ 
    alert ("both entries must be numbers!"); 
} 
else{ 
    low = parseFloat(low); 
    high = parseFloat(high); 
    return Math.floor(Math.random() * (high - low + 1)) + low; 
} 
+0

如果使用console.log()来显示提示收集的内容,它看起来是一个整数。为什么会这样? 此外,为什么方程不错误,并说NaN? –

相关问题