3 Replies - 428 Views - Last Post: 04 December 2012 - 02:21 PM

#1 StefanOnRails  Icon User is offline

  • D.I.C Head

Reputation: 35
  • View blog
  • Posts: 105
  • Joined: 31-July 12

pass an object as parameter

Posted 01 December 2012 - 06:01 PM

Hi,

Here's my problem:
function Pos()
{
	this.x;
	this.y;
}
...
var player = new Pos();
player.x = col;
player.y = row;
calculatePath(player);
...
function calculatePath(currentPos)
{
    var i = currentPos.y, j = currentPos.x; // Uncaught TypeError: Cannot read property 'y' of undefined
    ....
}

Is there anything wrong with the way I'm passing my object as a parameter?
Is This A Good Question/Topic? 0
  • +

Replies To: pass an object as parameter

#2 Dormilich  Icon User is online

  • 痛覚残留
  • member icon

Reputation: 3515
  • View blog
  • Posts: 10,144
  • Joined: 08-June 10

Re: pass an object as parameter

Posted 01 December 2012 - 06:30 PM

I tested it (FF17) and it worked without problem (as I would expect).
Was This Post Helpful? 0
  • +
  • -

#3 StefanOnRails  Icon User is offline

  • D.I.C Head

Reputation: 35
  • View blog
  • Posts: 105
  • Joined: 31-July 12

Re: pass an object as parameter

Posted 02 December 2012 - 04:07 AM

I changed my code, but the error is still there.
Ussually the error occurs whenever I want to get the first element of a queue (a Pos object) via queue.shift() (I add it using queue.push(myObj));

I know it's weird, I but it doesn't happen all the time, sometimes I get this error instead:

"Uncaught TypeError: Cannot read property '3' of undefined at line:" if(map[i - 1][j] == map[i][j] - 1) . My 2D array is correctly built, so there's no posibility for this element to be undefined.

Maybe a full source code will help. Hopefully someone will take the time to look over it.

JS:
function Pos()
{
	this.x;
	this.y;
}

function addListenerOn(element, event, handler)
{
	if(element.addEventListener) element.addEventListener(event, handler, false);
	else if(element.attachEvent) element.attachEvent("on" + event, handler);
	else element[event] = handler;
}

function removeListenerFrom(element, event, handler)
{
	if(element.removeEventListener) element.removeEventListener(event, handler, false);
	else if(element.detachEvent) element.detachEvent("on" + event, handler);
	else element[event] = null;
}

// action vars
var generateMapButton;
var previewButton;
var createButton;

// algorithm vars
var block = "default", color ="#FFF";
var map, rows, cols;
var mouse = new Pos(), cheese = new Pos();
var queue = [];

function copyToNext()
{
	this.nextElementSibling.value = this.value;
}

function showInput()
{
	var values      = "<option>0</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>A</option><option>B</option><option>C</option><option>D</option><option>E</option><option selected>F</option>";
	var blockColor  = document.getElementById("blockColor");	
	var selectArray = blockColor.getElementsByTagName("select");
	
	for(var i = 0; i < selectArray.length; ++i)
	{	
		selectArray[i].innerHTML = values;
		if(i % 2 == 0) addListenerOn(selectArray[i], "change", copyToNext);
	}
	
	document.getElementById("mapDialog").style.display = "block";
}

function ctrls(e)
{
	var key = String.fromCharCode(e.which);
	switch(key)
	{
		case 'W' : block = "wall"; break;
		case 'D' : block = "default"; break;
		case 'C' : block = "cheese"; break;
		case 'M' : block = "mouse"; break;
	}
}

function enableControls()
{
	addListenerOn(document, "keyup", ctrls);
}

function disableControls()
{
	removeListenerFrom(document, "keyup", ctrls);
	block = "none";
}

function updateBlock()
{
	if(block == "none") return;
		
	var id = this.id;
	var limit = id.indexOf("_");
	var row = parseInt(id.substr(0, limit));
	var col = parseInt(id.substr(limit + 1));
		
	if(block == "default")
	{
		this.style.background = color;
		map[row][col] = 0;
	}
	else
	{
		switch(block)
		{
			case "mouse" : 
				map[row][col] = -2;
				mouse.x = col;
				mouse.y = row;
			break;
			case "cheese" : 
				map[row][col] = 0;
				cheese.x = col;
				cheese.y = row;
			break;
			case "wall" : 
				map[row][col] = -1; 
			break;
		}
		this.style.background = "url('img/" + block + ".png')";
	}
}

function generateMap()
{
	var r1 = document.getElementById("r1").value;
	var r2 = document.getElementById("r2").value;
	var g1 = document.getElementById("g1").value;
	var g2 = document.getElementById("g2").value;
	var b1 = document.getElementById("b1").value;
	var b2 = document.getElementById("b2").value;
	color  = "#" + r1 + r2 + g1 + g2 + b1 + b2;
	rows   = parseInt(document.getElementById("rows").value);
	cols   = parseInt(document.getElementById("cols").value);
	
	var mapContent = "";
	map = [];
	
	var mapDiv    = document.getElementById("map");
	mapDiv.width  = cols * 54 + "px";
	mapDiv.height = rows * 54 + "px";
	
	for(var i = 0; i < rows; ++i)
	{
		map.push([]);
		for(var j = 0; j < cols; ++j)
		{
			mapContent += "<div id='" + i + "_" + j + "' class='block' style='background: " + color + "'></div>";
			map[i].push(0);
		}
		mapContent += "<p style='clear: both'><p/>";
	}
	mapDiv.innerHTML = mapContent;
	
	var blockArray = document.getElementsByClassName("block");
	for(var index in blockArray)
		addListenerOn(blockArray[index], "click", updateBlock);
	
	document.getElementById("p_create").style.display = "block";
	document.getElementById("default").style.background = color;
	
	enableControls();
	printMap(map, rows, cols);
}

function printMap(a, rows, cols)
{
	var i, j;
	for(i = 0; i < rows; ++i)
	{
		for(j = 0; j < cols; ++j)
			if(a[i][j] >= 0) console.log(i + "," + j + ":  " + a[i][j] + "  ");
			else if(a[i][j] == -3) console.log(i + "," + j + ": (" + a[i][j] + ") ");
			else console.log(i + "," + j + ":  " + a[i][j] + "  ");
		console.log("\n");
	}
	console.log("--------------------------------\n");
}

function jackpot(currentPos)
{
	if(currentPos.x == cheese.x && currentPos.y == cheese.y) return true;
	return false;
}

function goBack()
{
	var i = cheese.y, j = cheese.x;

	while(map[i][j] != 1)
	{
		if(i >= 0)
		{
			if(map[i - 1][j] == map[i][j] - 1)
			{
				map[i][j] = -3;
				i--;
				continue;
			}
		}

		if(j < cols)
		{
			if(map[i][j + 1] == map[i][j] - 1)
			{
				map[i][j] = -3;
				j++;
				continue;
			}
		}

		if(i < rows)
		{
			if(map[i + 1][j] == map[i][j] - 1)
			{
				map[i][j] = -3;
				i++;
				continue;
			}
		}

		if(j >= 0)
		{
			if(map[i][j - 1] == map[i][j] - 1)
			{
				map[i][j] = -3;
				j--;
				continue;
			}
		}

	}

	map[i][j] = -3;
	
	printMap(map, rows, cols);
}

function calculatePath()
{
	var i = mouse.y, j = mouse.x, counter = 1;
	var block = new Pos();
	
	while(true)
	{
		if(i - 1 >= 0)
		{
			if(map[i - 1][j] == 0)
			{
				block.x = j;
				block.y = i - 1;
				map[i - 1][j] = counter;
				if(jackpot(block))
				{
					goBack();
					return;
				}
				queue.push(block);
			}
		}

		if(j + 1 < cols)
		{
			if(map[i][j + 1] == 0)
			{
				block.x = j + 1;
				block.y = i;
				map[i][j + 1] = counter;
				if(jackpot(block))
				{
					goBack();
					return;
				}
				queue.push(block);
			}
		}

		if(i + 1 < rows)
		{
			if(map[i + 1][j] == 0)
			{
				block.x = j;
				block.y = i + 1;
				map[i + 1][j] = counter;
				if(jackpot(block))
				{
					goBack();
					return;
				}
				queue.push(block);
			}
		}

		if(j - 1 >= 0)
		{
			if(map[i][j - 1] == 0)
			{
				block.x = j - 1;
				block.y = i;
				map[i][j - 1] = counter;
				if(jackpot(block))
				{
					goBack();
					return;
				}
				queue.push(block);
			}
		}

		block = queue.shift();
		
		i = block.y;
		j = block.x;
		counter = map[i][j] + 1;
	}
}

function createMap()
{
	disableControls();
	calculatePath();
	document.getElementById("mapDialog").style.display = "none";
	document.getElementById("p_create").style.display  = "none";
	generateMapButton.style.display = "none";
} 

function init()
{
	generateMapButton = document.getElementById("genMap");
	addListenerOn(generateMapButton, "click", showInput);
	previewButton = document.getElementById("preview");
	addListenerOn(previewButton, "click", generateMap);
	createButton = document.getElementById("create");
	addListenerOn(createButton, "click", createMap);
}

window.onload = init;

HTML:
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>Algo</title>
		<link rel="stylesheet" type="text/css" href="css/layout.css" />
	</head>
	<body>
	
		<div id="wrapper">
			<button id="genMap">Generate Map</button>
			<div id="mapDialog">
				<p>
					Array Size ( <input id="rows" class="boxField" type="text" value="9" maxlength="2" />
					&nbsp;x&nbsp;
					<input id="cols" class="boxField" type="text" value="15" maxlength="2" /> )
				</p>
				<p id="blockColor">
					Block Color:<br/> 
					<select id="r1" class="red"></select>
					<select id="r2" class="red"></select>
					<select id="g1" class="green"></select>
					<select id="g2" class="green"></select>
					<select id="b1" class="blue"></select>
					<select id="b2" class="blue"></select>
				</p>
				<p style="padding-top:5px">
					<button id="preview">Preview</button>
				</p>
			</div>
			<div id="p_create" style="display:none">
				<br/>
				<div id="default" class="block_type"></div>
				<div id="wall" class="block_type"></div>
				<div id="mouse" class="block_type"></div>
				<div id="cheese" class="block_type"></div>
				<button id="create">Create</button>
			</div>
			<br/>
			<div id="map"></div>
		</div>
		
		<script type="text/javascript" src="js/algo.js"></script>
	</body>
</html>

Was This Post Helpful? 0
  • +
  • -

#4 Dormilich  Icon User is online

  • 痛覚残留
  • member icon

Reputation: 3515
  • View blog
  • Posts: 10,144
  • Joined: 08-June 10

Re: pass an object as parameter

Posted 04 December 2012 - 02:21 PM

itís been a while. while testing your code Iíve found, thet you never properly instantiated the Pos() objects. they are always empty and therefore you get some havoc when you try to use its properties (which are undefined).

PS. you should definitely avoid using global values, theyíre hard to debug. why not writing the values of interest in an object so that you have all together? e.g.
var myobj = {
  value: "test",
  print: function() {
    console.log(myobj.value);
  }
};
// attached to some button
button.onclick = myobj.print;

Was This Post Helpful? 2
  • +
  • -

Page 1 of 1