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
相关产品推荐
相关产品推荐

