使用以下方法计算每个点的距离
Math.sqrt( Math.pow(x, 2) + Math.pow(y, 2) );
取最低的结果
var points = [
{x: 10, y: 20},
{x: 12, y: 18},
{x: 20, y: 30},
{x: 5, y: 40},
{x: 100, y: 2}
];
function d(point) {
return Math.pow(point.x, 2) + Math.pow(point.y, 2);
}
var closest = points.slice(1).reduce(function(min, p) {
if (d(p) < min.d) min.point = p;
return min;
}, {point: points[0], d:d(points[0])}).point;
closest;
// {x: 12, y:18}
你会注意到我们跳过了Math.sqrt
走到这里。正如 Mark Setchell 指出的,计算平方根是一种“最小公分母”运算;我们仍然可以通过获取最小的点来确定最近的点x^2 + y^2
value.