计算我的参数x,y在某个数组区间内

比如我的参数是x:100,y:80,我的数组是[{x:80,y:60},{x:110,y:90}]
用来比较x,y最接近我的数组的哪个?
循环完后发现只有x符合,这个也可以被返回。
望哪位大神帮忙解决下~

阅读 1.1k
1 个回答

没大看懂你要的是什么,我的理解是你想要距离x,y最近的点?

let arr = [{x:80,y:60},{x:110,y:90}], point = {x:100, y:80}

function dist2d(point1, point2){
    return Math.sqrt(Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2))
}
function getNearestCoord(point, coords) {
    let d, res = { dist: Infinity }

    for (let i = 0; i < coords.length; i++) {
        d = dist2d(point, coords[i]);
        if (d < res.dist) {
            res.dist = d;
            res.index = i
            res.point = coords[i]
        }
    }
    
    return res.point// ? res : null;
}

getNearestCoord(point, arr)  // {x: 110, y: 90}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题