作为一项练习,我试图通过一点点递归来设置一个怪物着火。工作正常,但是我希望在递归运行时使用按钮添加额外的损坏。到目前为止,所有使用按钮设置额外变量的函数都不起作用,因为在递归运行时我似乎无法找到影响变量的方法。基本上在下面的例子中,我想按一下按钮来执行当前的" if(monster === 55)..."部分代码正在做。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function print(text) { document.querySelector("#content").innerHTML += text + "\n"; }
</script>
<title>Monster</title>
</head>
<body>
<input type="button" id="btnPoke" value="Poke it" onclick="" />
<pre id="content"></pre>
<script type="text/javascript">
var monster = 100;
var extra = 10;
function setonfire(monster, extra) {
setTimeout(function () {
print("Monster: " + monster + ", Extra: " + extra);
if (monster > 0) {
if (monster === 55) {
monster = monster - extra;
print("Poke for an extra " + extra);
}
monster = monster - 5;
setonfire(monster, extra);
}
}, 200);
}
setonfire(monster, extra);
</script>
</body>
</html>
我希望这不是太傻,但我真的很茫然,可能陷入思想错误。我会喜欢任何输入,告诉我哪里有错误的概念。我的怀疑是范围问题或递归
答案 0 :(得分:1)
Javascript按值传递基元。因此,当您致电setonfire(monster, extra);
时,您将100的值传递给方法,它永远不会影响外部monster
变量。
您可以直接在方法中引用monster
对象。所以:
var monster = 100;
var extra = 10;
function setonfire(extra) {
setTimeout(function () {
print("Monster: " + monster + ", Extra: " + extra);
if (monster > 0) {
if (monster === 55) {
monster = monster - extra;
print("Poke for an extra " + extra);
}
monster = monster - 5;
setonfire(extra);
}
}, 200);
}
setonfire(extra);
否则将monster
作为对象,例如:
var monster = { health: 100 };
var extra = 10;
function setonfire(monster, extra) {
setTimeout(function () {
print("Monster: " + monster.health + ", Extra: " + extra);
if (monster.health > 0) {
if (monster.health === 55) {
monster.health = monster.health - extra;
print("Poke for an extra " + extra);
}
monster.health = monster.health - 5;
setonfire(monster, extra);
}
}, 200);
}
setonfire(monster, extra);
编辑:变量大小