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
你将在控制台中找到结果,请参见下面的屏幕截图:

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP