从对象数组中的另一个 class 调用方法?
call method from another class from array of objects?
我正在用 P5 做一个打砖块,我创建了一个 class 块,只是一个构造函数和一个绘制方法。
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');
}
}
在草图中class我填充了名为块的数组,我在绘制函数上调用它但是它抛出了这个错误
sketch.js:25 Uncaught TypeError: Cannot read 属性 '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();
}
}
您正在第二个循环中检查 i<=5
,您应该检查 `j<=5'
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);
}
}
它阻止块数组获得超过 6 个块,因为对于所有 i
大于 5 的块,内部块不会 运行。
function draw() {
for(let i=0; i<=blocks.length; i++){
//console.log('aasas');
console.log(blocks[i]);
blocks[i].draw();
noLoop();
}
}
问题是您正在迭代 blocks
,但是 i<=blocks.length
条件导致最后一个循环迭代评估 blocks[blocks.length]
,这将是 undefined
。
要解决此问题,您可以将条件更正为 i<blocks.length
,或使用 for...of
:
function draw() {
for (const block of blocks) {
block.draw();
noLoop();
}
}
我正在用 P5 做一个打砖块,我创建了一个 class 块,只是一个构造函数和一个绘制方法。
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');
}
}
在草图中class我填充了名为块的数组,我在绘制函数上调用它但是它抛出了这个错误 sketch.js:25 Uncaught TypeError: Cannot read 属性 '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();
}
}
您正在第二个循环中检查 i<=5
,您应该检查 `j<=5'
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);
}
}
它阻止块数组获得超过 6 个块,因为对于所有 i
大于 5 的块,内部块不会 运行。
function draw() {
for(let i=0; i<=blocks.length; i++){
//console.log('aasas');
console.log(blocks[i]);
blocks[i].draw();
noLoop();
}
}
问题是您正在迭代 blocks
,但是 i<=blocks.length
条件导致最后一个循环迭代评估 blocks[blocks.length]
,这将是 undefined
。
要解决此问题,您可以将条件更正为 i<blocks.length
,或使用 for...of
:
function draw() {
for (const block of blocks) {
block.draw();
noLoop();
}
}