Javascript find adjacencies -
i have "class" called block
. possesses 3 variables : x
, y
, , z
, three-dimensional coordinates, respectively. having trouble finding number of "neighbours" block. is, if this
shares face, edge, or vertex other
, should return true. so, block.neighbours()
returns number of neighbours block
. however, returning 0
rather expected 1
. code shown below:
var blocks = []; function block(x, y, z) { blocks.push(this); this.x = x; this.y = y; this.z = z; this.neighbours = function() { var n = 0; (var block in blocks) { if (block == this) { continue; } if (math.abs(block.x - this.x) <= 1 && math.abs(block.y - this.y) <= 1 && math.abs(block.z - this.z) <= 1) { n++; } } return n; }; } var b1 = new block(0, 0, 0); var b2 = new block(0, 1, 0); document.getelementbyid("box").innerhtml = b1.neighbours();
why function returning 0
? (note: before javascript have html <p id = "box"></p>
, , in paragraph shows 0
).
the bug in code for (var block in blocks) {
not iterating expect -- var block in blocks
iterates on property names 0
, 1
demonstrated here:
you fix doing this:
(var blockkey in blocks) { var block = blocks[blockkey];
jsfiddle: http://jsfiddle.net/yxzobjhb/2/
another way fix write this:
var blocks = []; function block(x, y, z) { blocks.push(this); this.x = x; this.y = y; this.z = z; this.neighbours = function() { var n = 0; blocks.foreach(function(block) { if (block != && math.abs(block.x - this.x) <= 1 && math.abs(block.y - this.y) <= 1 && math.abs(block.z - this.z) <= 1) { n++; } }, this); return n; }; } var b1 = new block(0, 0, 0); var b2 = new block(0, 1, 0); document.getelementbyid("box").innerhtml = b1.neighbours();
jsfiddle: http://jsfiddle.net/jlxw316c/2/
Comments
Post a Comment