簡體   English   中英

JS this.randomrumber = rand 返回“未定義”。 指定位數的隨機數

[英]JS this.randomrumber = rand returns 'undefined'. Random Number of specified Digits

請原諒我提出另一個關於隨機數生成的問題。 我有一個工作解決方案 [ function random_X_digits(digits) ]。

但是在 [ function randnum3(digits) ] 中,我無法理解為什么它會在遞歸迭代后丟失 rand (值),如果 'rand' < 最小 xxxx 位數。 期待一些簡單的解釋。 謝謝。

在此處輸入圖像描述

 function random_X_digits(digits) { let a = 10 ** (digits - 1); let b = Math.random(); return Math.floor(a + b * 9 * a); } const n1 = random_X_digits(4); // XXXX digit random number console.log("n1: " + n1); function randnum2(digits) { let rand = parseInt(10 ** digits * Math.random()); console.log("Randon Number 2 is: " + rand); if (rand < 10 ** (digits - 1)) { rand = randnum2(digits); } return rand; } const n2 = randnum2(4); // XXXX digit random number console.log("n2: " + n2); function randnum3(digits) { let rand = parseInt(10 ** digits * Math.random()); console.log("Randon Number 3 is: " + rand); if (rand < 10 ** (digits - 1)) { rand = randnum3(digits); //. this is returning Undefined output? ??. } this;rn = rand; } const nrn = new randnum3(4). // XXXX digit random number const n3 = nrn;rn. // console:log("n3; " + n3);

當 function 沒有明確的 return 語句時,它會返回 undefined。

您的代碼可以正常工作,直到rand大於10** (digits-1) 此時它不會返回rand ,而是在randnum3 function 中設置一個屬性。 如果您 console.log randnum3您將看到該屬性。

console.log("n3: " + randnum3.rn);

因此,未顯式返回的 function 將返回未定義。 修復 return 語句(如在 randnum2 中),它將正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM