JavaScript indexOf() returns -1 对于数组中已识别的对象

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

在为 HTML 5 游戏(使用 canvas)创建框架时,我注意到 JavaScript 语言有一个有趣的怪癖,我似乎不太明白!

具体来说,我创建了一个对象(节点)数组,我可以毫无问题地传递函数(如 "node"),但即使在确认该对象在控制台日志中被识别后,.indexOf() 方法似乎无法将所述对象识别为数组中的一项(给我通用的“-1”输出)。

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 Whosebug 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>

我的(相当简单的)猜测是对象在某种程度上不是这种基于数组的方法的有效输入。如果是这种情况,是否有符合 W3C 标准的方法来解决这个问题?

未测试,但问题似乎在于这三个函数

function GenNodes() {
        // Rest of code
    nodes[i]= new SeedNode()
}

function SeedNode() {
        //Rest of code
        DrawNode(this,this.x,this.y)
} 

function DrawNode(node,x_cen,y_cen) {

    // Rest of code
    console.log(nodes.indexOf(node))
    seeds.fillText(nodes.indexOf(node),x_cen,y_cen)
}

在函数 GenNodes 中,您尝试填充 nodes 数组但这将取决于 return 来自 SeedNode 函数。同样,此 SeenNode 依赖于 DrawNode 函数的 return。这意味着一旦 DrawNodeSeedNode 执行完毕,它就会将元素放入 nodes 数组中。但是在放置元素之前,您正在检查 indexOf nodes 数组中的元素 DrawNode

因此 returning -1 我认为根据 indexOf

上的文档是正确的

您试图在将节点添加到 nodes 之前打印索引。你将永远得到-1。总之,请把DrawNode移出SeedNode

function GenNodes() {
    for (var i=0; i<10; i++) {
        var node = new SeedNode()
        nodes.push(node)
        DrawNode(node,node.x,node.y)
    }
}

function SeedNode() {
    var node = {}
    node.shape = "circle"
    node.radius = "10"
    node.x = 730*Math.random() + 10
    node.y = 730*Math.random() + 10 
    return node 
} 

您遇到了范围界定问题。 nodes 永远不会在 DrawNode() 可以找到的任何地方声明。要修复它,请在任何函数外声明 nodes

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