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

JavaScript调用函数后存储变量值 仅返回最后一次运算结果问题求解

问题原因
  • 你代码中用var声明的c、f属于x函数的内部作用域变量,每次递归调用x()时都会重新声明赋值,上一轮的计算结果会被直接覆盖,无法留存累加
  • 原有alert total()存在语法错误,正确写法为alert(total())
  • 代码中未定义y、z两个判断变量,直接运行会报错,需要先给这两个变量赋值
解决方法

把累计求和的变量提到x函数外部,每次计算出当前乘积后追加到对应累计变量中,而不是直接覆盖变量值。

修正后代码
// 提前定义y、z示例值,可根据你的实际逻辑修改
const y = "yes"
const z = "yes"
// 全局声明累计变量,初始值设为0
let totalC = 0
let totalF = 0

x();
function x() {
  if (y === "yes") {
    var a = parseInt(prompt("Insert Number Here"))
    var b = parseInt(prompt("Insert Number Here"))
    // 累计相加,不直接赋值覆盖旧值
    totalC += a * b
    var cont = prompt("yes or no").toLowerCase();
    if (cont === "yes") {
      x();
    } else if (cont === "total") {
      alert(total());
    }
  } else if (z === "yes") {
    var d = parseInt(prompt("Insert Number Here"))
    var e = parseInt(prompt("Insert Number Here"))
    // 累计相加,不直接赋值覆盖旧值
    totalF += d * e
    var cont = prompt("yes or no").toLowerCase();
    if (cont === "yes") {
      x();
    } else if (cont === "total") {
      alert(total());
    }
  }
}

function total() {
  return `The total is $${totalC + totalF}`
}

如果你不想污染全局作用域,也可以把累计值作为参数传递给递归调用的x函数,上述写法是修改成本最低、最容易理解的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:27:03