在本文中,我们将探讨如何在不使用数学函数的情况下从数组中查找最小值和最大值。包括 math.min() 和 math.max() 在内的数学函数返回数组中传递的所有数字的最小值和最大值。
我们将使用与数学函数相同的功能,可以使用循环实现。
这将使用 for 循环迭代数组元素并更新与数组中的每个元素进行比较后,变量中的最小和最大元素。
找到大于最大值的值时,我们将更新最大变量,类似地更新最小值。
>
在下面的示例中,我们在不使用数学函数的情况下从数组中找出最大值和最小值。
立即学习“Java免费学习笔记(深入)”;
#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:如何在没有数学函数的情况下查找最小值/最大值?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号