我正在尝试制作一个游戏,它在随机 x 位置生成 3 个 block ,所有 block 都有自己的 x、y、w、h 我想知道如何让它制作 block0 var、block1 var和 for 循环中的 block2 var 这是我得到的:
function block() {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
ctx.fillRect(this.x, this.y, this.w, this.h);
}
for (let i = 0; i < 3; i++) {
var block[i] = new block(Math.floor(Math.random() * 6) * 100,0,100,100);
block[i]();
}
最佳答案
您可以使用数组来保存您的 block 。另外,我已将相关参数添加到 block()
函数中。
function block(x, y, w, h)
{
this.x = x;
this.y = y;
this.w = w;
this.h = h;
ctx.fillRect(this.x, this.y, this.w, this.h);
}
let blocks = [];
for (let i = 0; i < 3; i++)
{
blocks[i] = new block(Math.floor(Math.random() * 6) * 100, 0, 100, 100);
// or blocks.push(new block(Math.floor(Math.random() * 6) * 100, 0, 100, 100));
}
然后,您可以分别以 blocks[0]
、blocks[1]
和 blocks[2]
的形式访问这三个 block .
关于javascript - 如何创建一个每次都会生成一个新变量的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55428319/