gpt4 book ai didi

javascript - 如何提高对象方法的使用效率?

转载 作者:行者123 更新时间:2023-12-03 02:08:10 25 4
gpt4 key购买 nike

我正在创建一个小游戏。游戏有商店和包;您可以从商店购买元素并将其放入包中。每个项目在游戏中都有自己的作用,有两种类型的项目:A) 只能由 onclick 触发的项目和 B) 应该不断检查条件的项目,然后只运行一次。我需要帮助为 typeB 项目创建代码。

<body onload = "docReady()">
<img src = "img1.png" onclick = "buy(item1TypeA)" />
<img src = "img2.png" onclick = "buy(item2TypeA)" />
<img src = "img3.png" onclick = "buy(item1TypeB)" />
<img src = "img4.png" onclick = "buy(item2TypeB)" />
// et cetera //
<ul id = "bagContainer"> // LI items appended here // </ul>
</body>

function docReady()
{
item1 = { type:A, name:1, price:1000 };
item2 = { type:A, name:2, price:2000 };
item3 = { type:B, name:3, price:4000 };
item4 = { type:B, name:4, price:16000 };
// et cetera //
money = 100000;
}

function buy(item)
{
if (money >= item.price)
{
money -= item.price;
if (sameItem == item1)
{
var listItem = document.createElement("li");
listItem.textContent = sameItem.name;
listItem.addEventListener('click', function() { //code1A// });
document.getElementById("bagContainer").appendChild(listItem);
}
if (sameItem == item2)
{
var listItem = document.createElement("li");
listItem.textContent = sameItem.name;
listItem.addEventListener('click', function() { //code2A// });
document.getElementById("bagContainer").appendChild(listItem);
}
// no idea how I could write the code for typeB items //
}
}

B 类项目的代码应不断检查条件。如果满足条件,该项目应运行其单独的功能。我的问题是不断地检查;如果我使用 whileif,如何阻止代码在其功能完成后不断检查?

我怎样才能对此进行软编码?

最佳答案

您可以创建一个间隔,每隔 x 量(毫秒)检查一次条件,并在满足条件时使用 removeInterval 将其删除。要存储删除的间隔,您可以使用箭头函数保持在同一范围内,以使间隔内的函数能够访问 interval

if (sameItem == item3) {
var listItem = document.createElement("li");
listItem.textContent = sameItem.name;
const interval = window.setInterval(() => {
if (condition) {
//code
window.removeInterval(interval);
}
}, 1000); //or whatever frequency
document.getElementById("bagContainer").appendChild(listItem);
}

关于javascript - 如何提高对象方法的使用效率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49709264/

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