Jonathan Straus Jonathan Straus - 1 year ago 114
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

function DrawNode(node,x_cen,y_cen) {

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

<body onload='StartGame()'>

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



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 Source

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() {

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

function doTheOtherThing() {
  console.log("This works");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download