JavaScript 如何找到最小/最大值而不使用Math函数
在本文中,我们将学习如何在数组中找到最小和最大值,而不使用Math函数。我们知道Math.max()返回数组中传递的最大数字,而Math.min()返回传递的最小数字。
方法:可以使用循环来实现Math函数的相同功能,请遍历数组中的数字以找到数组中的最大和最小值。
我们将使用循环来检查数组中的所有元素。如果我们发现任何大于之前的“max”值的元素,我们将该值设置为最大值。同样地,我们继续检查任何小于“min”值的元素。如果我们得到这样的元素,我们将“min”的值替换为较小的值。因此,使用循环函数,我们可以得到输入数组/列表中的最大和最小值。
示例1:下面的示例将演示上述方法。
JavaScript
// Array of numbers where the maximum
// and minimum are to be found
const array = [-1, 2, -5, 8, 16];
// Setting a number of the given array as
// value of max and min we choose 0th index
// element as atleast one element should be
// present in the given array
let max = array[0], min = array[0];
for (let i = 0; i < array.length; i++) {
// If we get any element in array greater
// than max, max takes value of that
// larger number
if (array[i] > max) { max = array[i]; }
// If we get any element in array smaller
// than min, min takes value of that
// smaller number
if (array[i] < min) { min = array[i]; }
}
console.log("max = " + max);
console.log("min = " + min);
输出: 使用该方法找出数组的最大值和最小值。
max = 16
min = -5
示例2: 在这个示例中,我们将不使用函数来获取最大值和最小值。
Javascript
const arr = [-7,-10,8,6,5,4];
let max = arr[0]
let min = arr[0];
for (let i = 0; i < arr.length; i++) {
// If the element is greater
// than the max value, replace max
if (arr[i] > max) { max = arr[i]; }
// If the element is lesser
// than the min value, replace min
if (arr[i] < min) { min = arr[i]; }
}
console.log("Max element is: " + max);
console.log("Min element is:"+min);
输出:
Max element is: 8
Min element is:-10