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

问题描述 投票:0回答:1

我正在尝试制作一个游戏,它在随机x位置产生3个区块,所有x都有自己的x,y,w,h我想知道如何让它成为block0 var,block1 var和block2在for循环中的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]();
}
javascript for-loop variables indexing var
1个回答
1
投票

您可以使用数组来保存块。另外,我已经将相关参数添加到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]的形式访问这三个块。

© www.soinside.com 2019 - 2024. All rights reserved.