2016-01-18 79 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? –

相關問題