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
相关产品推荐
相关产品推荐

