【发布时间】:2016-06-30 03:01:31
【问题描述】:
在为 HTML 5 游戏创建骨架时(使用画布),我注意到关于 JavaScript 语言的一个有趣的怪癖,我似乎不太了解!
具体来说,我创建了一个对象(节点)数组,通过函数(作为“节点”)传递它没有问题,但即使在确认控制台日志中识别出所述对象后,.indexOf() 方法也没有' t 似乎将所述对象识别为数组中的一个项目(给我通用的“-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 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>
我的(相当简单的)猜测是对象在某种程度上不是这种基于数组的方法的有效输入。如果是这种情况,是否有符合 W3C 标准的方法来解决这个问题?
【问题讨论】:
-
恐怕您实际上接受了错误的答案。如果一个变量没有在本地声明,它将被 JS 解释器作为一个全局变量。真正的问题是您尝试在将对象添加到
nodes之前打印它。请在下面查看我的解决方案。
标签: javascript object indexof