判断三点是否共线 - JavaScript
共线点
位于同一条直线上的三点或更多点称为共线点。
如果由这三点形成的所有三对直线的斜率相等,则这三点位于同一条直线上。
例如,考虑二维平面上的三个任意点 A、B 和 C,如果:
slope of AB = slope of BC = slope of accepts
直线的斜率 -
直线的斜率通常由它与 x 轴正方向所成的角的正切值给出。
或者,如果我们有两个位于直线上的点,例如 A(x1, y1) 和 B(x2, y2),则直线的斜率可以计算为:
Slope of AB = (y2-y1) / (x2-x1)
让我们为这个函数编写代码:
Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.
示例
以下是代码:
const a = {x: 2, y: 4}; const b = {x: 4, y: 6}; const c = {x: 6, y: 8}; const slope = (coor1, coor2) => (coor2.y - coor1.y) / (coor2.x - coor1.x); const areCollinear = (a, b, c) => { return slope(a, b) === slope(b, c) && slope(b, c) === slope(c, a); }; console.log(areCollinear(a, b, c));
输出
以下是控制台输出:
true
广告