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

如何在gleich函数中正确使用rechenoperator2变量?

问题根源

  • 你代码里的rechenoperator2是rechenoperator1方法的局部入参,作用域仅局限在rechenoperator1函数内部,gleich函数默认没有访问权限,直接调用会报变量未定义错误。
  • 你原写法想把数字、运算符、第二个数字拼接成字符串后用parseInt转成运算结果的逻辑也是错误的,比如拼接得到的"1+2"用parseInt转换只会返回开头的1,不会执行算术运算。

正确实现方式

  1. 首先给你当前的类/组件新增一个实例属性,用来存储用户选择的运算符,作用是打通两个方法的数据传递
  2. 改写rechenoperator1方法,把入参rechenoperator2的值存到新增的实例属性上
  3. 改写gleich方法,根据存储的运算符类型执行对应的算术运算即可

改后代码示例

// 先在你的类里和feld1speicher、feld1等变量同级,新增存储运算符的属性
currentOperator: number | string;

gleich() {
    console.log("=");
    this.feld2speicher = this.feld1;
    let finalResult: number;
    // 根据存储的运算符执行对应运算
    switch(this.currentOperator) {
        // 这里的case值可以根据你实际传的rechenoperator2编码调整,比如你用1代表加、2代表减就改对应数值
        case '+':
            finalResult = this.feld1speicher + this.feld2speicher;
            break;
        case '-':
            finalResult = this.feld1speicher - this.feld2speicher;
            break;
        case '*':
            finalResult = this.feld1speicher * this.feld2speicher;
            break;
        case '/':
            finalResult = this.feld1speicher / this.feld2speicher;
            break;
        default:
            finalResult = 0;
    }
    this.feld1 = finalResult;
}

rechenoperator1(rechenoperator2: number) {
    console.log(rechenoperator2);
    this.feld1speicher = this.feld1;
    // 把运算符存到全局实例属性上,供gleich方法调用
    this.currentOperator = rechenoperator2;
    console.log(this.feld1speicher)
    this.feld1 = 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:24:03