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

Node.js控制台问询工具开发遇undefined错误求助

Node.js控制台工具undefined错误问题解决

问题根源

你的simpleInterest函数内部完成了随机数计算,但没有返回计算结果。JavaScript中,函数如果没有显式使用return语句返回值,默认会返回undefined,这就是控制台输出undefined的原因。

修正方法

只需要在simpleInterest函数中添加返回逻辑即可,有两种简洁写法:

写法1(显式return):

const simpleInterest = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

写法2(箭头函数单行省略写法):

const simpleInterest = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

完整修正后的代码

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const ask = msg => new Promise(resolve => 
  rl.question(msg, response => resolve(response))
);

const simpleInterest = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

const main = async () => {
  const min = await ask("min number: "); // 修正拼写错误:numer -> number
  const max = await ask("max number: ");
  console.log(simpleInterest(+min, +max));
  rl.close();
};

main();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:45:47