在为HTML5游戏创建框架时(使用画布),我注意到了一个有趣的关于JavaScript语言的怪癖,我似乎不太理解!
具体来说,我创建了一个对象(节点)数组,在传递函数(作为“节点”)时没有问题,但即使在确认控制台日志中识别了所述对象之后,.indexOf()
方法似乎也没有将said对象识别为数组中的一个项(给出了通用的"-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标准的方法来解决这个问题呢?
发布于 2016-06-29 19:28:44
尝试在将节点添加到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
}
发布于 2016-06-29 19:15:09
没有经过测试,但他的问题似乎贯穿了这三个功能
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
数组,但这将取决于SeedNode
函数的返回。同样,这个SeenNode
依赖于DrawNode
函数的返回。这意味着,一旦DrawNode
& SeedNode
执行完毕,它就会将元素放入nodes
数组中。但在放置元素之前,您要检查indexOf
中的nodes
数组中的元素,该元素位于DrawNode
中。
因此,根据indexOf上的文档,它正在返回-1,我认为这是正确的。
发布于 2016-06-29 19:30:16
你的范围有问题。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();
https://stackoverflow.com/questions/38113276
复制相似问题