2014-03-28 24 views
0

我正在制作一个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变量,和铬打印的所有它的属性,因为它通常会。但是当我尝试访问一个属性时,它给了我错误。这对某个人来说似乎很明显,但是当我花费数小时调试时,我必须跳过某些东西,所以不要害羞!

+0

你粘贴了一半的代码。你在哪里定义equlized,gridSize和grid?这就是你的问题所在。 – mpm

+0

你在哪里填充dpixel?你正试图从数组中获取它,但是你在哪里实际创建它并将它推到数组? – webdev

+0

很抱歉忘记了添加该零件。 –

回答

0

我发现了小毛病。像往常一样,这是我的弱点,数学。在我定义dpixel和颜色变量的行上,我不需要向索引添加1。我的数组已经默认存储索引为0-224的变量,所以基于0的循环是可以的。 我怀疑最后一个元素是给我的错误,但我无法证明它尽管我记录每个元素来检查它是否是未定义的。