You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS中randnum3递归后返回undefined问题咨询

randnum3递归后返回undefined的原因解释

问题代码

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

原因解释

  • randnum3是通过new作为构造函数调用的,但递归时你直接用randnum3(digits)调用,此时它是普通函数而非构造函数。
  • 这个函数作为普通函数执行时,内部没有任何return语句,返回值默认是undefined,导致rand被赋值为undefined。
  • 最后执行this.rn = rand,自然就把实例的rn属性设成undefined了。

额外说明:就算递归时用new randnum3(digits),也会生成新的实例,原实例的rn还是拿不到正确值——因为递归的是新对象,和当前实例的this完全无关。

内容的提问来源于stack exchange,提问作者GT_newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 09:40:16