我正在尝试应用勾股定理来查找点数组之间的距离,因为我遍历数组,然后吐出n
最近点的数量。我对如何获得 d: 迭代点和下一个点之间的距离感到困惑,以比较迭代点和之后的下一个 +1 点的距离,依此类推。我从我的点数组开始:
var points = [
{ id: 1, x: 0.0, y: 0.0 },
{ id: 2, x: 10.1, y: -10.1 },
{ id: 3, x: -12.2, y: 12.2 },
{ id: 4, x: 38.3, y: 38.3 },
{ id: 5, x: 79.0, y: 179.0 },
];
然后我想遍历它们并使用勾股定理为它与其他点之间距离的每个点创建一个新数组:
points.forEach((item) => {
var newArray = [item];
var pt = null;
var d = null;
for (var i = 0; i < points.length; i = i + 1) {
//compare this point with all of the other points
for (var j = i + 1; j < points.length; j = j + 1) {
//compute distance
var curr = Math.sqrt(Math.pow(points[i][0] - points[j][0], 2) + Math.pow(points[i][1] - points[j][1], 2));
//get the distance between each point and push to a new array
if (d === null || curr < d) {
o = points.id[i];
pt = points.id[j];
d = curr;
}
}
}
newArray.push = {
"id": o,
"pt": pt,
"d": d
};
console.log(newArray);
});
似乎我在这里的某些逻辑区域不正确,并且Cannot read property '0' of undefined
每当我尝试变化时,我都会不断收到随机错误。关于我做错了什么的任何建议?