查詢特殊陣列 - JavaScript


如果陣列滿足以下條件,則該陣列為特殊陣列 -

--All the elements at odd indices are odd.
--All the elements at even indices are even.

我們需要編寫一個 JavaScript 函式,該函式輸入一個數組,並檢查其是否為特殊陣列。

示例

以下是程式碼 -

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const isSpecial = (arr = []) => {
   for(let i = 0; i < arr.length; i++){
      if(arr[i] % 2 === i % 2){
         continue;
      };
      return false;
   };
   return true;
};
console.log(isSpecial(arr));

輸出

以下是控制檯中的輸出 -

true

更新時間: 2020 年 9 月 16 日

449 次檢視

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.