简体   繁体   English

如何在两个循环内访问数组中的对象?

[英]How to access objects in array inside two loops?

I'm using p5.js in this project, I wanted to make rectangles that will fill the entire canvas, so I coded this:我在这个项目中使用 p5.js,我想制作将填充整个画布的矩形,所以我编写了以下代码:

for (let x = 0; x < cols; x++) {
    for (let y = 0; y < rows; y++) {
        cx = w + x * w - w;
        cy = w + y * w - w;
        rect(cx, cy, w, w)
    }
}

and obviously it works but I needed to make a rectangle class, but I don't know how to draw them all onto the screen, here is the code after creating the class, it doesn't really work...显然它有效,但我需要制作一个矩形类,但我不知道如何将它们全部绘制到屏幕上,这是创建类后的代码,它并没有真正起作用......

for (let x = 0; x < cols; x++) {
    for (let y = 0; y < rows; y++) {
        cx = w + x * w - w;
        cy = w + y * w - w;        
        rects.push(new Rectangle(cx, cy, w));
        rects[x * y].show()
    }
}

Your index x * y is wrong, you need:你的索引x * y是错误的,你需要:

 rects[x * rows + y].show();

But you could also just take the last element:但你也可以只取最后一个元素:

 rects[rects.length-1].show();

More intuitive (and more readable, and more efficient) would be to first assign the new object to a separate variable:更直观(更易读、更高效)是首先将新对象分配给一个单独的变量:

 var rect = new Rectangle(cx, cy, w);
 rects.push(rect);
 rect.show();

Assuming that your rectangle class works how you want it to, you would just need to change the last line to:假设您的矩形类按照您希望的方式工作,您只需要将最后一行更改为:

rects[y + (x * rows].show();

After 10 minutes scratching my head... you would normally iterate through the rows and then then columns of each row. 10 分钟后,我摸不着头脑……您通常会遍历行,然后遍历每行的列。 This puts your data starting from left to right, rather than top to bottom.这会将您的数据从左到右,而不是从上到下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM