Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 比较多个点之间的距离_Javascript_Arrays_Iterator_Pythagorean - Fatal编程技术网

Javascript 比较多个点之间的距离

Javascript 比较多个点之间的距离,javascript,arrays,iterator,pythagorean,Javascript,Arrays,Iterator,Pythagorean,我试图应用毕达哥拉斯定理,在迭代数组时,求出一组点之间的距离,然后吐出最近点的数量。我不知道如何得到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 },

我试图应用毕达哥拉斯定理,在迭代数组时,求出一组点之间的距离,然后吐出最近点的数量。我不知道如何得到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);
});
points.forEach((项目)=>{
var newArray=[item];
var-pt=null;
var d=null;
对于(变量i=0;i

似乎我这里的某些逻辑区域不正确,每当我尝试变量时,我总是会遇到随机的
无法读取未定义的
错误的属性“0”。对我正在做的事情有什么不正确的建议吗

您当前对每个项目进行了三次迭代:您有一个
forEach
和一个嵌套的
for
以及另一个嵌套的
for
。您还尝试对
点[i][0]
点[j][0]
等进行数学运算,但这些点不存在-
点[j]
,例如,是具有
x
y
属性的对象,而不是带有数字标记的数组

如果给每个单独的点一个变量,并使用求幂运算符,则会更清楚:

var点=[
{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},
];
常量点对=[];
对于(设i=0;ia.distance-b.distance);

log(pointPairs.slice(0,5))您当前正在对每个项目进行三次迭代:您有一个
forEach
,其中一个嵌套的
for
,另一个嵌套的
for
。您还尝试对
点[i][0]
点[j][0]
等进行数学运算,但这些点不存在-
点[j]
,例如,是具有
x
y
属性的对象,而不是带有数字标记的数组

如果给每个单独的点一个变量,并使用求幂运算符,则会更清楚:

var点=[
{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},
];
常量点对=[];
对于(设i=0;ia.distance-b.distance);
log(pointPairs.slice(0,5))