未被捕获的TypeError:在绘制时无法读取未定义的属性“ show”sketch.js:49

问题描述

我在函数Spot()中指定了函数show(),但仍然出现Uncaught TypeError错误,并说在draw()中未定义它。

这是Javascript代码,我正在使用p5.js作为库。

var cols = 5;
rows = 5;
var grid = new Array(cols);

var w,h;

function Spot(i,j){
    this.x = i;
    this.y = j;
    this.f = 0;
    this.g = 0;
    this.h = 0;

    this.show = function(){
        fill(255);
        stroke(0);
        rect(this.x*w,this.y*h,w-1,h-1);
    }  
}

function setup(){
    createCanvas(400,400);
    console.log('A*');

    w = width/cols;
    h = height/rows;

    for(var i = 0; i < cols;i++){
        grid[i] = new Array(rows);
    }

    console.log(grid);
    
    for(var i = 0; i < cols;i++)
    {
        for(var j = 0; i < rows;i++)
        {
            grid[i][j] = new Spot(i,j);
        }
    }
}
function draw(){
    background(0);
    
    for(var i = 0; i < cols-1;i++)
    {
        for(var j = 0; j < rows-1; j++)
        {
            grid[i][j].show();
        }
    }
}
    body {
      padding: 0;
      margin: 0;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/sketch.js/1.1/sketch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>

我在chrome控制台中遇到此错误,并且在本地PC上将html作为Web服务器运行。(localhost:8000)

这是Google chrome控制台中错误的附件图片

enter image description here

我刚刚开始使用Java脚本,尽管进行了广泛搜索,但仍无法解决错误

如果有人知道它会很有帮助。 预先感谢

解决方法

看看您的设置循环。

在嵌套循环中,您增加了i值,而不是j值。

您还计算了setupdraw中不同的行/列索引。 这可能就是您想要的,只是我想指出。

rows/cols-1cols/rows

var cols = 5;
var rows = 5;
var grid = new Array(cols);

var w,h;

function Spot(i,j){
    this.x = i;
    this.y = j;
    this.f = 0;
    this.g = 0;
    this.h = 0;

    this.show = function(){
        fill(255);
        stroke(0);
        rect(this.x*w,this.y*h,w-1,h-1);
    }
}

function setup(){
    createCanvas(400,400);
    console.log('A*');

    w = width/cols;
    h = height/rows;

    for(var i = 0; i < cols;i++){
        grid[i] = new Array(rows);
    }

    console.log('grid: ',grid);
    
    for(var i = 0; i < cols-1;i++)
    {
        for(var j = 0; j < rows-1;j++)
        {
            grid[i][j] = new Spot(i,j);
        }
    }
}
function draw(){
    background(0);
    
    for(var i = 0; i < cols-1;i++)
    {
        for(var j = 0; j < rows-1; j++)
        {
            grid[i][j].show();
        }
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/sketch.js/1.1/sketch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...