Home  >  Article  >  Web Front-end  >  JavaScript: How to find min/max values ​​without math functions?

JavaScript: How to find min/max values ​​without math functions?

王林
王林forward
2023-08-24 13:09:091487browse

In this article, we will explore how to find the minimum and maximum values ​​from an array without using mathematical functions. Math functions including Math.min() and Math.max() return the minimum and maximum of all numbers passed in an array.

Method

We will use the same functionality as a math function, which can be implemented using a loop.

This will use a for loop to iterate over the array elements and update the minimum and maximum elements in the variable after comparing with each element in the array.

When a value greater than the maximum value is found, we update the maximum variable and similarly the minimum value.

>

Example

In the following example, we find the maximum and minimum values ​​from an array without using mathematical functions.

#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>

Output

After successfully executing the above program, the browser will display the following results-

Welcome To Tutorials Point

In the console you will find the result, see screenshot below -

JavaScript: How to find min/max values ​​without math functions?

The above is the detailed content of JavaScript: How to find min/max values ​​without math functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete