您好,欢迎访问一九零五行业门户网

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:如何在没有数学函数的情况下查找最小值/最大值?的详细内容。
其它类似信息

推荐信息