Maison > interface Web > js tutoriel > JavaScript : Comment trouver les valeurs min/max sans fonctions mathématiques ?

JavaScript : Comment trouver les valeurs min/max sans fonctions mathématiques ?

王林
Libérer: 2023-08-24 13:09:09
avant
1746 Les gens l'ont consulté

在本文中,我们将探讨如何在不使用数学函数的情况下从数组中查找最小值和最大值。包括 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>
Copier après la connexion

输出

成功执行上述程序后,浏览器将显示以下结果 -

Welcome To Tutorials Point
Copier après la connexion

在控制台中,您将找到结果,请参见下面的屏幕截图 -

JavaScript : Comment trouver les valeurs min/max sans fonctions mathématiques ?

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal