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

如何让JavaScript类方法不使用更新后的值计算燃油消耗?

修正Car类的燃油消耗计算逻辑

原代码中accelerate方法的燃油消耗计算依赖累计的distance属性,导致多次调用时燃油消耗不符合线性需求。只需调整燃油消耗的计算依据,改为基于本次加速的距离增量(即当前的pedalPressure)即可解决问题。

修改后的完整代码:

class Car {
    constructor(name){
        this.distance = 0;
        this.fuel =  100;
        this.pedalPressure = 0;
        this.name = name;
    }

    changePedalPressure(vl){
        this.pedalPressure += vl;
    }

    accelerate(){
        // 提取本次加速的距离增量
        const currentIncrement = this.pedalPressure;
        // 更新累计行驶距离
        this.distance += currentIncrement;
        // 燃油消耗仅基于本次增量的绝对值
        this.fuel -= Math.abs(currentIncrement);
    }
}

关键修改说明

  1. 新增临时变量currentIncrement存储本次加速的距离增量(即当前的pedalPressure值),避免后续属性更新影响计算
  2. 燃油消耗改为减去currentIncrement的绝对值,确保每次加速的燃油消耗只和当前踏板压力线性相关,与累计行驶距离无关

验证效果

  • 初始化后调用changePedalPressure(10),第一次调用accelerate:
    • distance变为10,fuel变为90(符合预期)
  • 第二次调用accelerate:
    • distance变为20,fuel变为80(与期望一致)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 01:01:07