[英]Javascript Object turns to undefined when accessing property
我正在制作一个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:无法读取未定义的属性'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像往常一样打印了其所有属性。 但是,当我尝试访问属性时,它给了我错误。 对于某些人来说,这似乎确实很明显,但是当我花费数小时进行调试时,我一定跳过了某些事情,所以不要害羞!
我发现了小故障。 像往常一样,这是我的弱点,数学。 在定义dpixel
和color变量的行上,我不需要在索引上加1。 我的数组已经默认存储了索引为0-224的变量,所以基于0的循环是可以的。 我怀疑最后一个元素给了我错误,但是尽管我记录了每个元素以检查是否未定义,但我无法证明它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.