call method from another class from array of objects?

pauish :

I´m doing an Arkanoid with P5 and I created a class Block, is just a constructor and a method draw.

class Block{
    constructor(widthBlock, heightBlock, x, y, colorBlock){
        this.widthBlock=widthBlock;
        this.heightBlock=heightBlock;
        this.x = x;
        this.y=y;
        this.colorBlock=colorBlock;
    }

    draw(){
        fill(this.colorBlock);
        rect(this.x, this.y, this.widthBlock, this.heightBlock);
        console.log('bloke');
    }
}

In the sketch class I filled the array called blocks and i call it on draw function but it throws this error sketch.js:25 Uncaught TypeError: Cannot read property 'draw' of undefined (line 25 is blocks[i].draw(); )

for(let i=0; i<=blockAmount; i++){
        for(let j=0; i<=5; i++){
            blocks.push(new Block(widthBlock*i, widthBlock*j ,widthBlock, 20, color('pink'))); 
            console.log(blocks.length);
        }
    }

function draw() {
    for(let i=0; i<=blocks.length; i++){
        //console.log('aasas');
        console.log(blocks[i]);
        blocks[i].draw();
        noLoop();
    }
}

Ja͢ck :
function draw() {
    for(let i=0; i<=blocks.length; i++){
        //console.log('aasas');
        console.log(blocks[i]);
        blocks[i].draw();
        noLoop();
    }
}

The problem is that you're iterating over blocks, but the i<=blocks.length condition causes the last loop iteration to evaluate blocks[blocks.length], which will be undefined.

To solve this, you can either correct the condition to i<blocks.length, or use for...of:

function draw() {
  for (const block of blocks) {
    block.draw();
    noLoop();
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=30015&siteId=1