我正在制作一个html5 javascript游戏(不是用画布),我需要一个类用于我的对象。该类是DPixel,所有对象都存储在一个名为grid的数组中。这里是类:Javascript对象在访问属性时变成undefined
var grid = new Array();
function DPixel(data, x, y, node) {
this.xpos = x;
this.ypos = y;
this.elem = node;
this.type = data[0];
/*The pixel will transfer colors as normal*/
if (this.type === "normal") {
this.type = "normal";
this.red = data[1];
this.green = data[2];
this.blue = data[3];
}
/*The pixel will not transfer colors to other pixels*/
else if (this.type === "border") {
this.type = "border";
this.red = 224;
this.green = 210;
this.blue = 54;
}
}
数组的实际人口处于设置功能,不会被调用,我测试过,一切都很好在那里。
function setup() { for(var x = 0; x < gridSize; x++) { for(var y = 0; y < gridSize; y++) { var red = Math.floor(Math.random()*256); var green = Math.floor(Math.random()*256); var blue = Math.floor(Math.random()*256); totalRed += red; totalGreen += green; totalBlue += blue; $("#grid").append("<div></div>"); $("#grid div:nth-child(" + (x * gridSize + y + 1) + ")").css("background-color", "rgb(" + red + "," + green + "," + blue + ")"); grid[grid.length] = (new DPixel(["normal", red, green, blue], x, y, $("#grid div:nth-child(" + (x * gridSize + y + 1) + ")"))); } } }
我从Chrome中得到的错误是:“遗漏的类型错误:无法读取属性未定义‘类型’”在它运行每秒几次我的更新方法。
我曾尝试的console.log()在dpixel变量,和铬打印的所有它的属性,因为它通常会。但是当我尝试访问一个属性时,它给了我错误。这对某个人来说似乎很明显,但是当我花费数小时调试时,我必须跳过某些东西,所以不要害羞!
你粘贴了一半的代码。你在哪里定义equlized,gridSize和grid?这就是你的问题所在。 – mpm
你在哪里填充dpixel?你正试图从数组中获取它,但是你在哪里实际创建它并将它推到数组? – webdev
很抱歉忘记了添加该零件。 –