javascript - 如何创建一个每次都会生成一个新变量的 for 循环

标签 javascript for-loop variables indexing var

我正在尝试制作一个游戏,它在随机 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/

相关文章:

java - 如何在 Java 中存储变量,以便下次启动 .jar 时可以使用它?

javascript - 使用 ejabberd、stropice.js、stropice.muc.js 和 stropice.roster.js 的存在问题

javascript - 如何强制 google chrome/firefox 使用 Internet explorer web 浏览器控件

JavaScript RegExp 不能使用两次?

python - 用单个 for 遍历嵌套列表

linux - 我想将不同的文件夹和其中的文件(所有文件夹都相同)复制到另一个文件夹 - unix

Java从给定的数组列表动态生成各种字段类型

arrays - Lisp 变量未绑定(bind)

javascript - 如何最好地在 JavaScript 中重构这组跨多个方法的重复触发调用?

c - while (getchar () != '\n' );