如何在 JavaScript 陣列中查詢不包括 undefined 元素的最大值?


我們需要編寫一個 JavaScript 函式,該函式接受一個數組,其中包含一些數字、字串和一些錯誤值。

我們的函式應該返回陣列中最大的數字。

例如 -

如果輸入陣列如下,其中包含一些 undefined 值 -

const arr = [23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'];

則輸出應為 65

示例

以下是程式碼 -

const arr = [23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'];
const pickBiggest = arr => {
   let max = -Infinity;
   for(let i = 0; i < arr.length; i++){
      if(!+arr[i]){
         continue;
      };
      max = Math.max(max, +arr[i]);
   };
   return max;
};
console.log(pickBiggest(arr));

輸出

這將在控制檯上產生以下輸出 -

65

更新於: 01-10-2020

177 瀏覽量

事業衝刺

完成課程即可獲得認證

開始
廣告
© . All rights reserved.