動態型別陣列中最大數


我們需要編寫一個 JavaScript 函式,該函式接受一個包含一些數字、一些字串和一些 false 值的陣列。我們的函式應該從陣列中返回最大的數字。

例如:如果輸入陣列為 -

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

更新日期: 2020 年 10 月 24 日

100 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.