假设我有一个观点,称为i,即
{
x: 10000,
y: 10000
}
Run Code Online (Sandbox Code Playgroud)
我还有一些其他的观点,在一个数组中,比如:
[{
x: 35,
y: 10001
}, {
x: 2478,
y: 38
}, ...]
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何在 JavaScript 中从 获取最近的点i?谢谢!
您可以通过采用点的欧氏距离来减少数组,并采用距离较小的点。
function distance(p) {
return Math.sqrt(Math.pow(point.x - p.x, 2) + Math.pow(point.y - p.y, 2))
}
var point = { x: 10000, y: 10000 },
points = [{ x: 35, y: 10001 }, { x: 2478, y: 38 }],
closest = points.reduce((a, b) => distance(a) < distance(b) ? a : b);
console.log(closest);Run Code Online (Sandbox Code Playgroud)
您可以使用一些基本几何图形来创建一个函数,获取两点的绝对距离,然后循环遍历数组并找到给出最小距离的对象。
let p = {
x: 10000,
y: 10000
}
let arr = [{
x: 35,
y: 10001
}, {
x: 2478,
y: 38
}]
function getDiaDist(point){
return Math.sqrt(Math.pow(point.x,2) + Math.pow(point.y,2))
}
function getDistance(p1,p2){
return getDiaDist({x:p1.x - p2.x, y:p1.y - p2.y})
}
function getNearestPoint(arr,point){
let min = Infinity;
let result = arr[0]
arr.forEach(a => {
let dist = getDistance(a,point);
if(dist > min){
min = dist
result = a;
}
})
return result;
}
console.log(getNearestPoint(arr,p))Run Code Online (Sandbox Code Playgroud)