Jonathan Straus Jonathan Straus - 5 months ago 27
Javascript Question

Javascript indexOf() returns -1 for recognized objects in array

While create the skeleton for an HTML 5 game (using canvas), I noticed an interesting quirk about the JS language that I don't seem to quite understand!

Specifically, I created an array of objects (nodes) which I have no problem passing through functions (as "node"), but even after confirming that said object is recognized in the console log, the .indexOf() method doesn't seem to recognize said object as an item in the array (giving me the generic "-1" output).



function StartGame(){
//Initiating draw variables
cx = document.getElementById("GameMap")
seeds = cx.getContext("2d")
//Resetting nodes
nodes = []
GenNodes() //randomly generates and scatters new connector nodes on the game-map
}

function GenNodes() {
for (i=0; i<10; i++) {
nodes[i]= new SeedNode()
}
}

function SeedNode() {
this.shape = "circle"
this.radius = "10"
this.x = 730*Math.random() + 10
this.y = 730*Math.random() + 10
DrawNode(this,this.x,this.y)
}

function DrawNode(node,x_cen,y_cen) {
console.log(node)
console.log(nodes.indexOf(node))
seeds.beginPath();
seeds.arc(x_cen,y_cen,10,0,2*Math.PI);
seeds.stroke();
seeds.fillText(nodes.indexOf(node),x_cen,y_cen)
}

<!DOCTYPE html>
<html>
<head>
<title>ScatterDots! the StackOverFlow Edition</title>
<script src="ScatterDots.js"></script>
</head>

<body onload='StartGame()'>

<canvas id="GameMap" width="750" height="750" style="border:1px solid #000000"></canvas>

</body>

</html>





My (rather unsophisticated) guess is that objects are somehow not a valid input for this array-based method. If this is the case, are there W3C standards-compliant ways to get around this? Thanks!

Answer

You have a scoping problem. nodes is never declared anywhere that DrawNode() can find it. To fix it, declare nodes outside any function:

var testMe = [];
function doSomething() {
  doTheThing();
}

function doTheThing() {
  testMe[0] = "hi";
  testMe[1] = "there";
  doTheOtherThing();
}

function doTheOtherThing() {
  console.log("This works");
  console.log(testMe.indexOf("there"));
}

doSomething();