在 JavaScript 中检查直线
我们需要编写一个接收数组数组的 JavaScript 函数。每个子数组会包含两个项目,分别表示 x 和 y 坐标。
我们的函数应该检查由这些子数组指定的坐标是否形成一条直线。
例如 −
[[4, 5], [5, 6]] should return 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP