在 JavaScript 中检查直线
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 JavaScript 函数,该函数接受一个数组数组。每个子数组将包含两个项目,分别代表 x 和 y 坐标。
我们的函数应该检查这些子数组指定的坐标是否形成一条直线。
例如 −
[[4, 5], [5, 6]] 应该返回 true。
保证数组至少包含两个子数组。
示例
其代码为 −
const coordinates = [
[4, 5],
[5, 6]
];
const checkStraightLine = (coordinates = []) => {
if(coordinates.length === 0) return false;
let x1 = coordinates[0][0];
let y1 = coordinates[0][1];
let slope1 = null;
for(let i=1;i<coordinates.length;i++){
let x2= coordinates[i][0];
let y2= coordinates[i][1];
if(x2-x1 === 0){
return false;
}
if(slope1 === null){
slope1 = (y2-y1) / (x2-x1);
continue;
}
let slope2 = (y2-y1) / (x2-x1);
if(slope2 != slope1){
return false;
}
}
return true;
};
console.log(checkStraightLine(coordinates));
解释
我们确定每个点的斜率,如果斜率相等,则第一个点为直线,否则,如果其中一个点的斜率不同,则意味着点不在同一条线上。
输出
控制台中的输出将是 −
true
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

