【发布时间】:2021-12-10 12:28:23
【问题描述】:
我正在参加名为“僵尸猛攻”的 Codewars 挑战。
任务是:给定三个参数(n°僵尸,初始僵尸位置/距离,n°弹药) 我必须根据某些条件返回一条消息。
如果僵尸都死了,我应该返回:'You killed all ${x} zombies'
如果周围还有僵尸但你的弹药用完了我应该返回:'You shot ${x} zombies before being eaten: ran out of ammo.'
如果我有弹药但距离为 0,我应该返回 'You shot ${x} zombies before being eaten: overwhelmed.'
最后如果我的弹药用完了而且距离也是0,我应该返回'You shot ${x} zombies before being eaten: overwhelmed.'
现在问题是 console.log() 中消息显示正确,但我需要返回它,返回的只是一个undefined
这是代码,这是一个简短的函数,所以我把它都贴在这里。
function zombie_shootout(zombies, range, ammo) {
let currentZombies = zombies
let currentRange = range
let currentAmmo = ammo
let killedZombies = 0
let message = ''
setInterval(() => {
currentZombies -= 1
currentRange -= 0.5
currentAmmo -= 1
if (currentZombies === 0) {
message = `You shot all ${currentZombies} zombies`
} else if (currentZombies > 0 && currentAmmo === 0) {
killedZombies = zombies - currentZombies
message = `You shot ${killedZombies} zombies before being eaten: ran out of ammo.`
} else if (currentAmmo > 0 && currentRange === 0) {
killedZombies = zombies - currentZombies
message = `You shot ${killedZombies} zombies before being eaten: overwhelmed.`
} else if (currentAmmo === 0 && currentRange === 0) {
killedZombies = zombies - currentZombies
message = `You shot ${killedZombies} zombies before being eaten: overwhelmed.`
}
}, 1000)
return message
}
最后返回的message变量总是返回undefined
你们能帮帮我吗?因为在控制台中结果是正确的,所以一切似乎都正常。
这里有一些测试用例
zombie_shootout(3, 10, 10) // => "You shot all 3 zombies."
zombie_shootout(100, 8, 200) // => "You shot 16 zombies before being eaten: overwhelmed."
zombie_shootout(50, 10, 8) // => "You shot 8 zombies before being eaten: ran out of ammo."
【问题讨论】:
-
在返回
message时,没有赋值。 -
看看
setInterval()做了什么。以及为什么您当前的设置根本无法工作。 -
你为什么在你的函数中使用
setInterval()? o.O -
是的,当然 setInterval 需要修改。但我试图把 if 语句放在区间之外,它没有用。
-
@D.D.显示您尝试没有
setInterval的代码,并解释“不起作用”的含义。