【问题标题】:How do I make a for loop that makes a new variable everytime如何创建一个每次都生成一个新变量的 for 循环
【发布时间】:2019-08-21 00:53:55
【问题描述】:

我正在尝试制作一个游戏,它在随机 x 位置的 3 个块中生成,它们都有自己的 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]();
}

【问题讨论】:

    标签: javascript for-loop variables indexing var


    【解决方案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] 的身份访问这三个块。

    【讨论】:

    • 我假设这个人已经声明了数组,但只是没有将它包含在他们发布的代码的范围内。如果不是,那么这是一个相当有趣的简单解决方案。
    • @MaxVoisard 但是他试图在循环的每次迭代中定义一个像var block[i] 这样的新变量,我不相信他使用数组。
    • 你很有可能是对的。他还尝试定义一个包含数组索引的变量,而不是数组本身,这就是为什么它会不断为同一个变量重新定义不同的值。
    猜你喜欢
    • 1970-01-01
    • 2014-08-03
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多