首頁 > web前端 > js教程 > 主體

JavaScript:如何在沒有數學函數的情況下找到最小值/最大值?

王林
發布: 2023-08-24 13:09:09
轉載
1653 人瀏覽過

在本文中,我們將探討如何在不使用數學函數的情況下從陣列中找到最小值和最大值。包括 Math.min()Math.max() 在內的數學函數傳回陣列中傳遞的所有數字的最小值和最大值。

方法

我們將使用與數學函數相同的功能,可以使用循環實作。

這將使用 for 循環迭代數組元素並更新與數組中的每個元素進行比較後,變數中的最小和最大元素。

找到大於最大值的值時,我們將更新最大變量,類似地更新最小值。

>

範例

在下面的範例中,我們在不使用數學函數的情況下從陣列中找出最大值和最小值。

#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
登入後複製

在控制台中,您將找到結果,請參見下面的螢幕截圖-

JavaScript:如何在沒有數學函數的情況下找到最小值/最大值?

#

以上是JavaScript:如何在沒有數學函數的情況下找到最小值/最大值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!