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

如何在JavaScript函数中让增量操作达到50后停止每次加10

问题原因

你的代码存在两个核心逻辑错误,直接导致测试不通过:

  • drink方法内的判断条件误用了形参ouncesDrank,而非实例自身的this.ouncesDrank属性,测试用例调用drink时没有传入参数,形参始终为undefined,满量判断逻辑永远不会触发
  • 累加操作写在了判断逻辑之前,哪怕判断逻辑正确,第六次调用方法时也会先把数值加到60再做校验,不符合「达到50就停止累加」的要求
修正后代码
class Vampire {
  constructor(name, otherPet){
    this.name = name;
    this.pet = otherPet || "bat";
    this.thirsty = true;
    this.ouncesDrank = 0;
  }
  drink(){
    // 先判断是否已经喝满50
    if(this.ouncesDrank >= 50){
      return 'I\'m too full to drink anymore!';
    }
    // 没满再执行累加和状态修改
    this.thirsty = false;
    this.ouncesDrank += 10;
  }
};
修正说明
  • 移除了无用的形参ouncesDrank,所有逻辑直接操作实例自身的ouncesDrank属性
  • 调整了逻辑顺序:调用方法时先判断是否已经喝满50,满量直接返回提示,不执行后续累加操作
  • 仅当未喝满时,才更新口渴状态和已喝数值,完全匹配测试用例的预期逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:30:04