gpt4 book ai didi

javascript - addEventListener 和数组内部的值递减问题

转载 作者:行者123 更新时间:2023-12-03 00:09:20 25 4
gpt4 key购买 nike

我在数组内部使用 addEventListener 时遇到了问题。我的目标是每次点击后减少“敌人”的生命值。添加一些代码进行解释:

var image;
var enemy = [];

function start()
{
image = document.getElementById("image");

enemy.push(new createEnemy());

draw()
}

function draw()
{
if(enemy[0].hp <= 0) enemy.splice(0 , 1); /*Also, will my splice work
if instead of enemy[0] a "for loop" with (if(enemy[i].hp <= 0) enemy.splice(i, 1);)
was used?*/

requestAnimationFrame(draw);
}

function createEnemy()
{
this.hp = 2; //Value to be decreased
this.image = document.getElementById("image");
this.image.addEventListener("click", function()
{
console.log("Click works but hp doesn't decrease");
this.hp--; //Problem cause
})
}
<!DOCTYPE html>
<html>
<body onload="start()">
<img id="image" src="https://i.imgur.com/hZWobCv.gif">
</body>
</html>

此外,如果“敌人”的生命值达到 0,是否有比在动画帧中使用拼接更简单的方法来摧毁他们?

最佳答案

回调函数有自己的this,使用箭头函数代替:

this.image.addEventListener("click", () =>
{
console.log("Click works but hp doesn't decrease");
this.hp--; // will use the parent's this.hp
})

var image;
var enemy = [];

function start() {
image = document.getElementById("image");

enemy.push(new createEnemy());

draw()
}

function draw() {
if (enemy[0].hp <= 0) enemy.splice(0, 1); //Also, will my splice work if instead of enemy[0] a "for loop" with (enemy[i], enemy.splice(i, 1);) was used?

requestAnimationFrame(draw);
}

function createEnemy() {
this.hp = 10; //Value to be decreased
this.image = document.getElementById("image");
this.image.addEventListener("click", () => {
console.log("Click works , this.hp = ", this.hp);
this.hp--;
})
}
<!DOCTYPE html>
<html>

<body onload="start()">
<img id="image" src="https://i.imgur.com/hZWobCv.gif">
</body>

</html>

关于javascript - addEventListener 和数组内部的值递减问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54816862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com