我正在制作一个html5 javascript游戏(不是用画布),我需要一个类用于我的对象。该类是DPixel,所有对象都存储在名为 grid 的数组中。这是班级:
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得到的错误是:“Uncaught TypeError:在我的update方法中,每秒运行几次,无法读取未定义的属性'type'。
function update() {
console.log("update is working");
//Update each DPixel
var rotations = 0;
for(var x = 0; x < gridSize; x++) {
for(var y = 0; y < gridSize; y++) {
var dpixel = grid[x * gridSize + y + 1];
var pixelType = dpixel.type; //The error is here
var red = grid[x * gridSize + y + 1].red;
var green = grid[x * gridSize + y + 1].green;
var blue = grid[x * gridSize + y + 1].blue;
rotations++;
}
}
$("#equalized").html(equalized);
$("#equalPercent").html( (equalized / (gridSize*gridSize))*100 );
updateID = setTimeout(update, $("input[type='range']").val());
}
我在dpixel变量上尝试过console.log(),并且chrome通常会打印所有属性。但是当我尝试访问属性时,它会给我错误。对某些人来说这似乎是显而易见的,但是当我花了几个小时的调试时,我必须跳过一些东西,所以不要害羞!
答案 0 :(得分:0)
我发现了一点小故障。像往常一样,这是我的弱点,数学。在我定义dpixel
和颜色变量的行上,我不需要在索引中添加1。我的数组默认存储了索引为0-224的变量,因此基于0的循环是可以的。
我怀疑最后一个元素给了我错误但我无法证明它尽管我记录了每个元素以检查它是否未定义。