我的代码存在很多问题..这是我的代码。
var playerDogHealth = [10, 10, 10];
var playerDogAttentionAll = [10, 10, 0];
function healthDecreaseTime() {
// Health, Hunger, Attention
if (playerDogAttentionAll[0] == 0 <= 5) {
playerDogHealth[0] = playerDogHealth[0] - 2;
} else {
playerDogHealth[0] = playerDogHealth[0] - 1;
}
console.log(playerDogHealth[0]);
}
setInterval(healthDecreaseTime(),1000);
healthDecreaseTime();
当我在控制台中查看时,我看到的只是'9'然后是'8'然后就是它......它因某种原因停止减少。一些帮助将非常感激。
答案 0 :(得分:2)
只需删除()
。
所以而不是:
setInterval(healthDecreaseTime(),1000);
写:
setInterval(healthDecreaseTime,1000);
<强>更新强>:
setInterval
要求第一个参数为函数。
所以healthDecreaseTime
==功能
但healthDecreaseTime()
==函数返回的内容(在您的情况下为undefined
)
答案 1 :(得分:1)
删除()
- 将调用该函数并返回其结果(undefined
),而不是传递函数本身。如果您没有首先将该功能传递给setInterval
,那该怎么知道该怎么称呼?
var playerDogHealth = [10, 10, 10];
var playerDogAttentionAll = [10, 10, 0];
function healthDecreaseTime() {
// Health, Hunger, Attention
if (playerDogAttentionAll[0] <= 5) {
playerDogHealth[0] = playerDogHealth[0] - 2;
} else {
playerDogHealth[0] = playerDogHealth[0] - 1;
}
console.log(playerDogHealth[0]);
}
setInterval(healthDecreaseTime, 1000);
healthDecreaseTime();
此外,您似乎偶然包含了== 0
,这应该只是
if (playerDogAttentionAll[0] <= 5) {
事实上,您可以将if-else条件简化为以下内容:
playerDogHealth[0] -= playerDogAttentionAll[0] <= 5 ? 2 : 1;