我们需要编写一个包含数组的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