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

Node.js使用readline多输入后调用函数返回NaN的问题求助

问题分析与解决方案

核心问题

  1. 变量未正确赋值:question1/question2/question3的回调函数中,money/rate/time是局部参数,并未更新你声明的全局变量,导致全局的money/rate/time始终为undefined,传入simpleInterest计算时,undefined * undefined * undefined结果就是NaN。
  2. 函数内变量未声明:simpleInterest函数中直接使用simpleInterest=money*rate*time,未用let/const声明,会覆盖函数本身(非严格模式下),严格模式下还会报错。

优化后的代码

推荐尽量避免全局变量,改为让每个question函数返回输入值,在main中接收并使用:

function simpleInterest(money, rate, time) {
  // 用const声明局部变量,避免覆盖函数名
  const interest = money * rate * time;
  return interest;
}

'use strict'

const readline = require('readline')

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

const question1 = () => {
  return new Promise((resolve) => {
    rl.question('Total Money: ', (input) => {
      // 将输入转为数字并返回
      resolve(Number(input));
    })
  })
}

const question2 = () => {
  return new Promise((resolve) => {
    rl.question('Interest Rate: ', (input) => {
      resolve(Number(input));
    })
  })
}

const question3 = () => {
  return new Promise((resolve) => {
    rl.question('How Many Years: ', (input) => {
      resolve(Number(input));
    })
  })
}

const main = async () => {
  // 直接接收每个问题的返回值
  const money = await question1();
  const rate = await question2();
  const time = await question3();
  
  let profit = simpleInterest(money, rate, time);
  console.log("total", profit);
  rl.close();
}

main();

关键修改点

  • 每个question函数的Promise返回转换为数字的输入值,避免字符串相乘导致的问题。
  • main函数中直接用变量接收输入值,不再依赖全局变量,代码更清晰安全。
  • 修正simpleInterest函数内的变量声明,使用const interest存储计算结果,避免覆盖函数本身。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:36:14