简体   繁体   English

JS this.randomrumber = rand 返回“未定义”。 指定位数的随机数

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

pardon me for putting up another question on random number generation.请原谅我提出另一个关于随机数生成的问题。 I have a working solution as [ function random_X_digits(digits) ].我有一个工作解决方案 [ function random_X_digits(digits) ]。

But in [ function randnum3(digits) ], I failed to understand why it loses rand (value) after recursive iteration it goes under if 'rand' < minimum xxxx digit number.但是在 [ function randnum3(digits) ] 中,我无法理解为什么它会在递归迭代后丢失 rand (值),如果 'rand' < 最小 xxxx 位数。 looking forward for some simple explanations.期待一些简单的解释。 Thanks.谢谢。

在此处输入图像描述

 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);

When a function doesn't have an explicit return statement, it returns undefined.当 function 没有明确的 return 语句时,它会返回 undefined。

Your code works fine until rand is greater than 10** (digits-1) .您的代码可以正常工作,直到rand大于10** (digits-1) At that point it doesn't return rand , but sets a property in the randnum3 function.此时它不会返回rand ,而是在randnum3 function 中设置一个属性。 If you console.log randnum3 you will see that property.如果您 console.log randnum3您将看到该属性。

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

So, a function that doesn't return explicitly, returns undefined.因此,未显式返回的 function 将返回未定义。 Fix the return statement (like in randnum2) and it will work properly.修复 return 语句(如在 randnum2 中),它将正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM