JavaScript:如何在没有数学函数的情况下查找最小值/最大值?
在本文中,我们将探讨如何在不使用数学函数的情况下从数组中查找最小值和最大值。包括 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