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

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

王林
Release: 2023-08-24 13:09:09
forward
1704 people have browsed it

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>
Copy after login

Output

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

Welcome To Tutorials Point
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template