JavaScript:如何在不使用 Math 函式的情況下查詢最小/最大值?


在本文中,我們將探討如何在不使用 Math 函式的情況下從陣列中查詢最小值和最大值。Math 函式包括 Math.min()Math.max(),它們返回陣列中所有數字中的最小值和最大值。

方法

我們將使用 Math 函式可以使用迴圈實現的同樣功能。

這將使用 for 迴圈遍歷陣列元素,並在將它與來自陣列的每個元素進行比較後,在變數中更新最小元素和最大元素。

在找到大於最大值的值時,我們將更新 max 變數,對於 min 值也是如此。

示例

在下面的示例中,我們在不使用 Math 函式的情況下找出陣列中的最大值和最小值。

#Filename: index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Find Min and Max</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome to Tutorials Point
   </h1>
   <script>
      // Defining the array to find out
      // the min and max values
      const array = [-21, 14, -19, 3, 30];

      // Declaring the min and max value to
      // save the minimum and maximum values

      let max = array[0], min = array[0];
      for (let i = 0; i < array.length; i++) {
         // If the element is greater
         // than the max value, replace max
         if (array[i] > max) { max = array[i]; }

         // If the element is lesser
         // than the min value, replace min
         if (array[i] < min) { min = array[i]; }
      }
      console.log("Max element from array is: " + max);
      console.log("Min element from array is: " + min);
   </script>
</body>
</html>

輸出

在成功執行上述程式後,瀏覽器將顯示以下結果:

Welcome To Tutorials Point

你將在控制檯中找到結果,請參見下面的螢幕截圖:

更新於:2022 年 4 月 26 日

2K+ 瀏覽量

開啟你的職業生涯

完成該課程獲得認證

開始
廣告