无法读取对象的属性

时间:2015-02-10 06:26:26

标签: javascript

我在代码中花了很多时间处理这个烦人的问题。我定义了一个类来保存几个属性。然后我将这些属性填充到二维数组中。然后,我尝试修改2d数组中的随机元素。我一直收到消息

"Cannot read property of 'attribute' of undefined"

其中attribute是我对象中三个属性中的任何一个。这是我的代码:



var table = new Array();
var adjacencyList = new Array();

var cell = function (prop) {
	var atrbs = {
		x: prop.x,
		y: prop.y,
		isVisited: prop.isVisited
	}
	return atrbs;
};

var createTable = function(size){
	for(var row = 0; row < size; row++){
		table[row] = new Array();
		for(var column = 0; column < size; column++){
			table[row][column] = new cell({x: row, y: column, isVisited: false});
		}
	}
};

function print(){
	for(var row = 0; row < table.length; row++){
		for(var column = 0; column < table[row].length; column++){
			console.log(table[row][column]);
		}
	}
};

var randomizeMaze = function(){
	var randomX = Math.floor((Math.random() * table.length));
	var randomY = Math.floor((Math.random() * table.length));
	var currentCell = table[randomX][randomY];
	currentCell.isVisited = true;
	adjacencyList.push(currentCell);

	while( adjacencyList.length > 0 ) {

		currentCell.isVisited = true;
		var adjacentNodes = getAdjacentNodes(currentCell);
		//randomly select a node to add to path
		var nextInPath = adjacentNodes[Math.floor((Math.random() * adjacentNodes.length))];
		//add to path to not visit it again
		adjacencyList.push.apply(adjacencyList, adjacentNodes);
		var removeNode = adjacencyList.indexOf(currentCell);
		adjacencyList.splice(removeNode, 1);

		//reset currentCell to random cell from resized list
		currentCell = adjacencyList[Math.floor((Math.random() * adjacencyList.lenth))];
	}
};

function getAdjacentNodes(pCell){
	
	var adjacentNodes = new Array();
	//check left
	if(pCell.x - 1 >= 0){
		var node = table[pCell.x-1][pCell.y];
		adjacentNodes.push(node);
		adjacencyList.push(node);
	}
	//check right
	if(pCell.x + 1 < table.length){
		var node = table[pCell.x+1][pCell.y];
		adjacentNodes.push(node);
		adjacencyList.push(node);
	}
	//check top
	if(pCell.y - 1 >= 0){
		var node = table[pCell.x][pCell.y - 1];
		adjacentNodes.push(node);
		adjacencyList.push(node);
	}

	//check bottom
	if(pCell.y + 1 < table.length){
		var node = table[pCell.x][pCell.y + 1];
		adjacentNodes.push(node);
		adjacencyList.push(node);
	}
	return adjacentNodes;
};

createTable(3);
//print();
randomizeMaze();
&#13;
&#13;
&#13;

每当我尝试访问/更改单元格内的任何属性时,即在函数&#39; randomeMaze&#39;和&#39; getAdjacentNodes&#39;,它会抛出我提到的错误。我可以将对象打印到控制台,我在调试时看到对象被填充。也许我错过了一些东西而且我会发疯。

非常感谢任何帮助。

0 个答案:

没有答案