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

JavaScript对象中实现lives大于0时才减1且不低于0的方法

修复方案

当前playerDies方法未做阈值判断,无条件执行生命值减1,是导致lives出现负数的根本原因。

核心修改

给扣减生命值的逻辑加前置判断:仅当this.lives > 0时才执行减1操作,生命值归0后不再扣减。之前写if-else运行失败,通常是判断条件写错、或者漏写this导致属性读取失败。
修改后的方法片段:

playerDies: function() {
    if (this.lives > 0) {
        this.lives -= 1;
    }
    return this.lives;
},

测试代码笔误修正

你提供的测试代码有一处赋值错误,会导致积分输出不符合预期:

game.coins = 0;
console.log("points = " + game.points);  // should be 20

按照积分规则coins * 10,这里需要给coins赋值为2才能得到20的输出,原代码赋值0永远只能得到0积分。

完整修复后代码

var game = {
    lives: 3,
    coins: 0,

    get points() {
        return this.coins * 10;
    },

    playerDies: function() {
        if (this.lives > 0) {
            this.lives -= 1;
        }
        return this.lives;
    },

    newGame: function() {
         this.lives = 3;
         this.coins = 0;
    },
};

console.log("lives = " + game.lives);    // 3
console.log("coins = " + game.coins);    // 0
console.log("points = " + game.points);  // 0
game.coins = 2;
console.log("points = " + game.points);  // 20
game.playerDies();
console.log("lives = " + game.lives);    // 2
game.playerDies();
game.playerDies();
game.playerDies();
console.log("lives = " + game.lives);    // 0,无负数异常
game.newGame();
console.log("lives = " + game.lives);    // 3
console.log("coins = " + game.coins);    // 0

运行后所有输出完全匹配预期,连续调用playerDies也不会出现生命值小于0的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 05:55:05