在 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

更新於: 20-11-2020

389 次瀏覽

開啟你的 職業生涯

完成課程,即可獲得認證

立即開始
廣告