我有一个"班级"叫Block
。它拥有三个变量:x
,y
和z
,分别是它们的三维坐标。我无法找到"邻居的数量"到一个街区。也就是说,如果this
与other
共享一个面,边或顶点,它应该返回true。因此,block.neighbours()
会将邻居数返回block
。但是,它返回0
而不是预期的1
。我的代码如下所示:
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;
for (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();
为什么函数返回0
? (注意:在javascript之前我有html <p id = "box"></p>
,并在段落中显示0
)。
答案 0 :(得分:0)
代码中的错误是for (var block in blocks) {
没有按预期迭代 - var block in blocks
遍历0
和1
的属性名称,如下所示:
你可以通过这样做来解决它:
for (var blockKey in blocks) {
var block = blocks[blockKey];
JSFiddle:http://jsfiddle.net/yxzobjhb/2/
另一种解决方法是将其写成:
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 != this && 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/
答案 1 :(得分:0)
for ... in
语句返回键,而不是地图/数组的实际值。您必须在每次迭代中查找块,例如
var key, block;
for (key in blocks) {
block = blocks[key]
/* ... */
}
答案 2 :(得分:0)
You shouldn't use for...in
with arrays.但是,如果这样做,它会获取属性名称,而不是值。你必须这样做:
for (var index in blocks) {
var block = blocks[index];
在现有代码中,block
是0
第一次迭代,1
是第二次迭代。
但是,你应该使用它:
for(var i = 0; i < blocks.length; i++){
var block = blocks[i];