使用 JavaScript 查找二维平面中两点之间的距离


问题

我们需要编写一个 JavaScript 函数,该函数接收两个对象,这两个对象都具有 x 和 y 属性,用于指定平面中的两个点。

我们的函数应该查找并返回这两个点之间的距离。

示例

以下为代码 -

 在线演示

const a = {x: 5, y: -4};
const b = {x: 8, y: 12};
const distanceBetweenPoints = (a = {}, b = {}) => {
   let distance = 0;
   let x1 = a.x,
   x2 = b.x,
   y1 = a.y,
   y2 = b.y;
   distance = Math.sqrt((x2 - x1) * 2 + (y2 - y1) * 2);
   return distance;
};
console.log(distanceBetweenPoints(a, b));

Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.

输出

6.164414002968976

更新时间: 17-4-2021

344 次浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告