Javascript - Uncaught TypeError: Cannot read property 'show' of undefined
Javascript - Uncaught TypeError: Cannot read property 'show' of undefined
我在 p5.js 中制作一个非常简单的绘图网络应用程序时遇到了错误。
错误说它在第 10 行,但我没有看到错误?也许我对数组做错了。
var pixels = [];
var drawing = false;
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
background(0);
for(var i = pixels.length - 1;i >= 0;i++) {
pixels[i].show();
}
if(drawing) {
var nP = new Pixel(mouseX, mouseY);
pixels.push(nP);
}
}
function mousePressed() {
drawing = true;
}
function mouseReleased() {
drawing = false;
}
function Pixel(x, y) {
this.x = x;
this.y = y;
this.show = function() {
push();
noStroke();
fill(255);
rect(this.x, this.y, 10, 10);
pop();
}
}
问题在行-
for(var i = pixels.length - 1;i >= 0;i++)
为了向后遍历数组,您需要递减计数器,而不是递增它。所以,正确的循环应该是-
for(var i = pixels.length - 1;i >= 0;i--)
我在 p5.js 中制作一个非常简单的绘图网络应用程序时遇到了错误。 错误说它在第 10 行,但我没有看到错误?也许我对数组做错了。
var pixels = [];
var drawing = false;
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
background(0);
for(var i = pixels.length - 1;i >= 0;i++) {
pixels[i].show();
}
if(drawing) {
var nP = new Pixel(mouseX, mouseY);
pixels.push(nP);
}
}
function mousePressed() {
drawing = true;
}
function mouseReleased() {
drawing = false;
}
function Pixel(x, y) {
this.x = x;
this.y = y;
this.show = function() {
push();
noStroke();
fill(255);
rect(this.x, this.y, 10, 10);
pop();
}
}
问题在行-
for(var i = pixels.length - 1;i >= 0;i++)
为了向后遍历数组,您需要递减计数器,而不是递增它。所以,正确的循环应该是-
for(var i = pixels.length - 1;i >= 0;i--)